How to set _id to db document in Mongoose?

You either need to declare the _id property as part of your schema (you commented it out), or use the _id option and set it to false (you’re using the id option, which creates a virtual getter to cast _id to a string but still created an _id ObjectID property, hence the casting error you get).

So either this:

var Post = new mongoose.Schema({
    _id: Number,
    title: String,
    content: String,
    tags: [ String ]
});

Or this:

var Post = new mongoose.Schema({
    title: String,
    content: String,
    tags: [ String ]
}, { _id: false });

Leave a Comment