Is data returned from Mongoose immutable?

前端 未结 3 915
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 20:03

I want to add to the return data from a mongoose query:

User.findById(userId, function(err, data) {
  if (!err) {
    data.newvar = \'Hello, world\';
  }
});         


        
相关标签:
3条回答
  • 2021-01-01 20:30

    As it turns out, Mongoose documents are their own special class and not standard Javascript objects. In order to get a javascript option that can be extended, you must use the toObject() method.

    0 讨论(0)
  • Now you can use lean() method to return a plain js object:

    User.findById(userId)
      .lean()
      .exec( function(err, data) {
        if (!err) {
          data.newvar = 'Hello, world';
        }
      });
    

    Why can't you modify the data returned by a Mongoose Query (ex: findById)

    0 讨论(0)
  • 2021-01-01 20:56

    One way to handle this is to convert your mongoose model instance into a plain object that you have full control over by calling toObject() on it:

    User.findById(userId, function(err, data) {
      if (!err) {
        data = data.toObject();
        data.newvar = 'Hello, world';
      }
    });
    

    If you want a more structured solution, you can add virtual attributes to your schema as described here.

    0 讨论(0)
提交回复
热议问题