How to get array of json objects rather than mongoose documents

纵然是瞬间 提交于 2019-12-31 10:07:44

问题


When I do find operation like the follows:

Collection.find({name: 'Erik'}, function (err, docs) {
   // do momething
});

'docs' variable is populated with an array of fully functional mongoose documents. But I need to get an array of pure JSON objects.

I know I can loop through the 'docs' array by forEach and get an objects by using .toJSON() method. Does mongoose support the feature I'm interested?


回答1:


If you're using Mongoose 3.x you can use the lean query option to do this:

Collection.find({name: 'Erik'}).lean().exec(function (err, docs) {
    // docs are plain javascript objects instead of model instances
});



回答2:


.exec(function(err, docs){
    docs= docs.map(o => o.toObject());

This will include virtuals and getters



来源:https://stackoverflow.com/questions/12210870/how-to-get-array-of-json-objects-rather-than-mongoose-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!