Add a dynamic property to a Mongoose result with _.each
Mongoose documents don't allow adding properties. You need to either call the lean()
method before exec()
since documents returned from queries with the lean option enabled are plain javascript objects.
From the docs:
Font.find().lean().exec(function (err, docs) { docs[0] instanceof mongoose.Document // false});
So your code should look like:
Font.find() .lean() .exec(function (err, fonts) { if(err) return res.send(err); _.each(fonts, function(item, i) { item.joined_name = item.name + item.style.replace(/\s/g, ''); console.log(item.joined_name); // works fine }); res.send(fonts); });
or cast the returned document to a plain object:
Font.find() .exec(function (err, docs) { if(err) return res.send(err); var fonts = []; _.each(docs, function(item, i) { var obj = item.toObject(); obj.joined_name = obj.name + obj.style.replace(/\s/g, ''); console.log(obj.joined_name); fonts.push(obj); }); res.send(fonts); });