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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With