Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can remove _id from embedded object in Mongoose schema? [duplicate]

I have this Mongoose schema:

const User = mongoose.model('User', new Schema({
    id: String,
    name: String,
    extra: { bb: Number, chain: Number }
}), 'users');

When I see a new User, it's stored like this:

{ 
  _id: ...,
  id: '1234',
  name: 'John',
  extra: {
    _id: ...,
    bb: 54,
    chain: 7
  },
  __v: 1
}

As you see, Mongoose (or Mongo, I don't know) is including a _id in embedded object extra. Why is that happening? How can I prevent it to happen?

like image 800
Héctor Avatar asked Aug 27 '18 20:08

Héctor


1 Answers

You can declare "_id: false" for a subschema as shown below.

const User = mongoose.model('User', new Schema({
     id: String,
     name: String,
     extra: { bb: Number, chain: Number, _id: false }
}), 'users');
like image 107
NeedMoreVolume Avatar answered Sep 20 '22 03:09

NeedMoreVolume