无法向 js 对象添加属性 [英] Unable to add properties to js object
本文介绍了无法向 js 对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要返回一个 Mongoose 文档,并希望在发送之前向其中添加一些元数据.然而,我无法添加任何属性,我不知道为什么.我已经检查过它是否可以使用 Object.isExtensible(doc) 进行扩展,并且确实如此.
I am returning a Mongoose document and wish to add some meta data to it before I send it off. 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.
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
})
可能有什么问题?
推荐答案
啊.. 我的对象是一个不允许添加属性的 Mongoose 文档.解决方案是将返回的文档转换为普通对象或在查询中调用 Lean().
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.
Item.findById(req.params.id).exec(function(err, doc) {
var obj = doc.toObject();
...
});
Item.findById(req.params.id).lean().exec(function(err, doc) {
...
});
这篇关于无法向 js 对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文