简体   繁体   中英

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. In the response I get the object without the property 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).

One possible way around this is using lean() method to enable lean option. Quoting the doc :

Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments . They have no save method, getters/setters or other Mongoose magic applied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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