Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array of json objects rather than mongoose documents

Tags:

When I do the .find operation like the following:

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?

like image 880
Erik Avatar asked Aug 31 '12 07:08

Erik


2 Answers

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 }); 
like image 153
JohnnyHK Avatar answered Sep 21 '22 16:09

JohnnyHK


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

This will include virtuals and getters

like image 34
Uday Hiwarale Avatar answered Sep 19 '22 16:09

Uday Hiwarale