使用_.each将dynamic属性添加到Mongoose结果中

我想dynamic地添加一个属性到Mongoose结果的每个对象,但它不会按预期工作。

Font.find() .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); // `joined_name` property is nonexistant }); 

一定是简单的,但我不明白为什么。 欢迎替代品!

Mongoose文档不允许添加属性。 您需要在exec()之前调用lean()方法,因为启用了精简选项的查询返回的文档是纯javascript对象。

从文档:

 Font.find().lean().exec(function (err, docs) { docs[0] instanceof mongoose.Document // false }); 

所以你的代码应该是这样的:

 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); }); 

或将返回的文档转换为普通对象:

 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); });