Two duplicate ID fields(_id and id) automatically on populating

Viewed 683

While getting data from my database, I noticed that there is an extra id field other than the normal _id field. These 2 fields are exactly the same always. However, id and _id only comes when I am populating. Otherwise there is only the _id field. This is the schema -

const answerSchema = new mongoose.Schema({
    content: {
        type: String,
        required: [true, 'An answer must have a summary'],
    },
    user: {
        type: mongoose.Types.ObjectId,
        required: [true, 'An answer must have a user'],
    },
    post: {
        type: mongoose.Types.ObjectId,
        required: [true, 'An answer must belong to a post'],
        ref: 'Post',
    },
    users: [{ type: mongoose.Types.ObjectId, ref: 'User' }],
    isCorrect: {
        type: Boolean,
        default: false,
    },
});

answerSchema.pre(/^find/, function (next) {
    this.populate({
        path: 'post',
        select: '-answers -users',
    }).populate('user');
    next();
});

const Answer = mongoose.model('Answer', answerSchema);

Why does this happen and how do I fix it?

2 Answers

based on mongoose ref You can disable pass id to doc with this code:

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

One solution also could be :

  this.populate({
        path: 'post',
        select: '-answers -users -_id',
    }).populate('user');

you cannot exclude the id but mongoose let you exclude _id.

Related