Dushyant Bangal
Dushyant Bangal

Reputation: 6403

Mongoose keeps giving both _id and id with same value

I have some Mongoose schemas, whose certain fields need getter and setters.

For that, i've set the following:

MySchema.set('toObject',{getters:true});
MySchema.set('toJSON',{getters:true});

Whenever I send/read the result of MySchema.find(), it gives me both _id and id fields, which have same value. I think thats a virtual field (correct me if i'm wrong here)

How do i stop this? I don't want to process through each and every object and remove the field.

Upvotes: 3

Views: 2288

Answers (1)

robertklep
robertklep

Reputation: 203359

Documented here:

Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString. If you don't want an id getter added to your schema, you may disable it passing this option at schema construction time.

Just set the id field to false while creating the schema:

var schema = new Schema({ name: String }, { id: false });

Upvotes: 6

Related Questions