Home > Net >  Mongoose Add Extra Field To Object
Mongoose Add Extra Field To Object

Time:09-27

I want to add new field to object.

var _u = await User.findOne({_id},{_id:0, name:1, username:1, group:1}).populate({
  path: 'group',
  select: '-_id title'
})
_u.type = 'user'
console.log(_u)

But hasn't got type field. Why I can't add new field? What should I do?

CodePudding user response:

It's because Mongosee hydrate it's responses, so it's not pure JavaScript object.

If you want to return pure JavaScript object, you have to add lean() method to the query. Also, that will improve the performance.

await User.findOne({ _id }, { _id:0, name:1, username:1, group:1 })
  .populate({
    path: 'group',
    select: '-_id title'
  })
  .lean()

You can find more info in the official docs.

  • Related