Igor P.
Igor P.

Reputation: 1477

Mongoose: Add data to returned result set

Using mongoose in a MEAN environment, I need to add data to a returned mongoose query result. The query returns a list of authors. I want to add a thumbnail field (=calculated path of the thumbnail image) to each author in query result. This is my code (loop code missing for simplicity reasons):

var searchQuery = Author.find({ ...foo... }); 
searchQuery.limit(10);
//...

searchQuery.exec(function (err, authors) {
   authors.set('thumbnail', 'test'); //causes error, no effect
   res.json(authors);
});

I am aware that mongoose does not return a plain JS/JSON object, hence I need to convert the resultset first to be able to manipulate it. As a matter of fact nothing would work for me and I tried pretty much everything:

searchQuery.lean().exec(function (err, authors) { //lean() option makes no difference

Converting the result doesn't work either, as I keep getting the "[...] has no method 'xy'" error.

var tempresult = authors.toObject(); //--> causes error above
var tempresult = authors.toJSON(); //--> causes error above

What else may I have missed?

Upvotes: 12

Views: 6304

Answers (2)

Judson Terrell
Judson Terrell

Reputation: 4306

you can also just take the returned document in function(res,doc...) and do:

var docForMap = JSON.parse(JSON.stringify(doc));

This will give you a new copy that you can work with.

Upvotes: 3

JohnnyHK
JohnnyHK

Reputation: 311895

Once you convert the resulting docs to plain JS objects by using lean(), they won't have any of the Mongoose model instance methods available to them like set, so you need to directly manipulate them using normal JavaScript object techniques:

searchQuery.lean().exec(function (err, authors) {
   authors = authors.map(function(author) {
       author.thumbnail = 'test';
       return author;
   });
   res.json(authors);
});

If you want to maintain the results as mongoose docs, then you need to pass {strict: false} as a third parameter to set to allow arbitrary fields to be added:

searchQuery.exec(function (err, authors) {
   authors = authors.map(function(author) {
       author.set('thumbnail', 'test', {strict: false});
       return author;
   });
   res.json(authors);
});

Upvotes: 21

Related Questions