25

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?

1
  • 2
    An array of plain JavaScript objects Commented Aug 31, 2012 at 13:53

3 Answers 3

43

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

Note that lean is not the same as toJSON as it returns a raw dump from Mongo (meaning no virtuals are included). See this for more info
wow, they couldn't have made this more difficult to find. THANK YOU!
10
.exec(function(err, docs){
    docs= docs.map(o => o.toObject());

This will include virtuals and getters

Comments

0

Map through results and convert each to JS object:

const result = await model.find({some: 'query'});
return result.map((r) => r.toObject());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.