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'
}
Maybe a bit astray to the answer, but if anyone who is looking to do the other way around, you can use
Model.hydrate()
(since mongoose v4) to convert a javascript object (JSON) to a mongoose document.An useful case would be when you using
Model.aggregate(...)
. Because it is actually returning plain JS object, so you may want to convert it into a mongoose document in order to get access toModel.method
(e.g. your virtual property defined in the schema).PS. I thought it should have a thread running like "Convert json to Mongoose docs", but actually not, and since I've found out the answer, so I think it is not good to do self-post-and-self-answer.
I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:
doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.
First of all, try
toObject()
instead oftoJSON()
maybe?Secondly, you'll need to call it on the actual documents and not the array, so maybe try something more annoying like this:
It's a guess, but I hope it helps
You may also try mongoosejs's lean() :
You can use res.json() to jsonify any object. lean() will remove all the empty fields in the mongoose query.
UserModel.find().lean().exec(function (err, users) { return res.json(users); }
Try this options: