乐闻世界logo
搜索文章和话题

How do you turn a Mongoose document into a plain object?

1个答案

1

Mongoose is a MongoDB Object Document Model (ODM) library that provides a convenient way to model and handle MongoDB documents within the Node.js environment. Mongoose documents are special objects with additional features and behaviors. Sometimes we need to convert these documents into plain JavaScript objects for JSON serialization or to simplify processing logic.

To convert Mongoose documents to plain objects, you can use the .toObject() method, which returns a clean JavaScript object that excludes all special features and additional properties of the Mongoose document. Additionally, when you call the .toJSON() method, it internally calls .toObject() and applies the json transformation options defined in the schema.

Here is an example demonstrating how to use the .toObject() method:

javascript
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // Define a Schema const userSchema = new Schema({ name: String, age: Number }); // Create Model const User = mongoose.model('User', userSchema); // Query document User.findById('User ID').exec((err, doc) => { if (err) throw err; if (doc) { // Convert Mongoose document to plain object const plainObject = doc.toObject(); // Now you can process plainObject as a regular object console.log(plainObject); } });

Within the .toObject() method, you can also pass options to customize the conversion result:

javascript
const plainObject = doc.toObject({ getters: true, // Apply schema-defined getters virtuals: true, // Include virtual properties versionKey: false, // Exclude __v property (version key) transform: function (doc, ret, options) { // Custom transformation logic delete ret._id; // Exclude _id property return ret; } });

In real-world development, this feature is very useful. For example, before returning query results to the frontend, you can first convert them to plain objects to remove unnecessary information or adjust the object structure to meet the frontend's data requirements.

2024年6月29日 12:07 回复

你的答案