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

How to convert Mongoose docs to json

1个答案

1

In Mongoose, converting documents to JSON is intuitive and flexible. The Mongoose model provides the .toJSON() method, which converts a Mongoose document into a plain JSON object. This method is particularly useful when sending query results to the client or processing data further within the application.

Using the .toJSON() Method

After retrieving a Mongoose document from the database, you can directly call .toJSON() to convert it. Here is a specific example:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: String, age: Number, email: String }); const User = mongoose.model('User', userSchema); User.findById('some user ID').exec((err, user) => { if (err) throw err; const jsonUser = user.toJSON(); console.log(jsonUser); // This outputs a plain JSON object });

Customizing the .toJSON() Method

Mongoose allows you to customize the behavior of .toJSON(). For instance, you might want to exclude sensitive fields like the user's password or email from the JSON output. You can achieve this by using the toJSON option when defining the schema:

javascript
const userSchema = new Schema({ name: String, age: Number, email: String, password: String }, { toJSON: { transform: (doc, ret) => { delete ret.password; return ret; } } }); const User = mongoose.model('User', userSchema); // When calling toJSON, the password field is excluded from the output. User.findById('some user ID').exec((err, user) => { if (err) throw err; console.log(user.toJSON()); // The output JSON object excludes the password field });

By doing this, you can control which information is converted to JSON, thereby better protecting user data privacy or simplifying client-side data processing workflows.

2024年8月12日 10:53 回复

你的答案