Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Mongoose docs to json

I returned mongoose docs as json in this way:

UserModel.find({}, function (err, users) {     return res.end(JSON.stringify(users)); } 

However, user.__proto__ was also returned. How can I return without it? I tried this but not worked:

UserModel.find({}, function (err, users) {     return res.end(users.toJSON());    // has no method 'toJSON' } 
like image 274
Trantor Liu Avatar asked Mar 31 '12 03:03

Trantor Liu


People also ask

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

To turn a Mongoose document into a plain object, we can use the lean method. MyModel. findOne(). lean().

What is toJSON mongoose?

Mongoose toObject and toJSON transform behavior with sub-documents. Published on Tuesday, June 7, 2016. Mongoose supports two Schema options to transform Objects after querying MongoDb: toObject and toJSON . In general you can access the returned object in the transform method toObject or toJSON as described in the ...

What does res JSON () do?

json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.


1 Answers

You may also try mongoosejs's lean() :

UserModel.find().lean().exec(function (err, users) {     return res.end(JSON.stringify(users)); } 
like image 151
ecdeveloper Avatar answered Oct 13 '22 04:10

ecdeveloper