How can I modify an object returned by a Mongoose query?
Assume we have the following schema:
var S = new mongoose.Schema( { 'name': String, 'field': String } );
I do the following query and modification to the result:
var retrieve = function(name, callback) {
S.findOne({ name: name }).exec(function (err, obj) {
if (err) return handleError(err);
obj['field'] = 'blah';
callback(obj);
});
}
The obj.field will not contain blah but the original value returned by the query, as if it was read-only. What is going on?
Note: my environment is Node.js, Express, Mongoose and MongoDB
Note: This is an edit, my original answer was rather different
So this is a little confusing but Mongoose returns MongooseDocument objects and not plain JSON objects. So use the .lean() method on obj which will turn it into JSON, and from there you start altering it as you wish.
With thanks to Ze Jibe.
The doc object returned from mongoose is somehow read only. To get a writeable object from it you must run:
var writeableObject = doc.toObject()
writeableObject['field'] = 'blah'
res.send(writeableObject)
Scroll down to "Transform" in the mongoose documentation to read more: link