Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 757
Akash Avatar asked Nov 22 '25 22:11

Akash


1 Answers

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

new Schema({ name: String }, { id: false });
like image 163
hesam mosleh Avatar answered Nov 25 '25 11:11

hesam mosleh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!