Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
Igor P. Avatar asked Dec 10 '14 10:12

Igor P.


1 Answers

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);
});
like image 97
JohnnyHK Avatar answered Nov 11 '22 16:11

JohnnyHK