[英]Unable to add properties to js object
I am returning a Mongoose document and wish to add some meta data to it before I send it off.我正在返回一个 Mongoose 文档,并希望在发送之前向其中添加一些元数据。 I am however unable to add any properties and I am not sure why.
然而,我无法添加任何属性,我不知道为什么。 I have checked that it is extensible with Object.isExtensible(doc) and it is.
我已经检查过它是否可以使用 Object.isExtensible(doc) 进行扩展,并且确实如此。
Item.findById(req.params.id).exec(function(err, doc) {
doc.blah = 'hello';
console.log(doc); // No trace of 'blah'. I can change/delete existing props however
})
What could be issue?可能是什么问题?
Ah.. My object is a Mongoose document which doesn't allow adding properties.啊..我的对象是一个不允许添加属性的猫鼬文档。 The solution is to either convert the returned document to a plain object or to call lean() in the query.
解决方案是将返回的文档转换为普通对象或在查询中调用 Lean()。
Item.findById(req.params.id).exec(function(err, doc) {
var obj = doc.toObject();
...
});
Item.findById(req.params.id).lean().exec(function(err, doc) {
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.