Sometimes, we want to modify the data returned by a Mongoose query in Node.js.
In this article, we’ll look at how to modify the data returned by a Mongoose query in Node.js.
How to modify the data returned by a Mongoose query in Node.js?
To modify the data returned by a Mongoose query in Node.js, we can call lean
to make Mongoose return a plain object version of the query result that we can modify.
For instance, we write
Survey.findById(req.params.id).lean().exec((err, data) => {
data.surveyQuestions.forEach((sq) => {
Question.findById(sq.question, (err, q) => {
sq.question = q;
});
});
});
to call lean
after call findById
to make the data
in the exec
callback a plain JavaScript object version of the query result.
We then loop through each item in data.surveyQuestions
and set sq.question
to q
on each entry in the Question.findById
callback.
Conclusion
To modify the data returned by a Mongoose query in Node.js, we can call lean
to make Mongoose return a plain object version of the query result that we can modify.