简体   繁体   English

向现有属性添加新属性无效

[英]adding a new property to existing doesn't work

I'm trying to add another property to existing object returning from findOne() promise in mongoose. 我试图将另一个属性添加到从猫鼬的findOne()许诺返回的现有对象中。 In the response I get the object without the property convertName 在响应中,我得到的对象没有属性convertName

app.get('/getItem', (req, res) => {

var itemID = req.query.itemID;

Item.findOne({_id: itemID}).then(item => {

    item.convertName = 'cm';
    res.send(item);

  }).catch( err => {
    res.status(401).send();
  });
})

I know that the way to add another property to an existing object is similar to this, just specify the property name and set a value to it, so I don't know why it is not working in this case. 我知道向现有对象添加另一个属性的方法与此类似,只需指定属性名称并为其设置一个值,所以我不知道为什么在这种情况下它不起作用。

Hope you can explain and help me why its not working. 希望您能解释并帮助我为什么它不起作用。

It's a bit complicated with Mongoose: by default MongooseDocument is returned by query, and the property that you try to add to such a document is not reflected on its serialized value (the one that is sent in the response). Mongoose有点复杂:默认情况下, MongooseDocument是由查询返回的,而您尝试添加到此类文档的属性不会反映在其序列化值(响应中发送的值)上。

One possible way around this is using lean() method to enable lean option. 解决此问题的一种可能方法是使用lean()方法启用lean选项。 Quoting the doc : 引用文档

Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments . 从启用了lean选项的查询返回的文档是纯javascript对象,而不是MongooseDocuments They have no save method, getters/setters or other Mongoose magic applied. 他们没有应用保存方法,吸气剂/设置器或其他猫鼬魔法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM