Unable to get _id which is not ObjectID with mongoose

Viewed 713

I can't access to _id of any mongoose.model object. I know there are a lot of similar answers but none of it solved my problem. I am using mongoose and TypeScript.

I've existing collection which contains data with existing Mixed _id:

{
   _id: 10,
   name: "someString",
   email: "someString",
}
...

I've Schema and interface:

const UserModel: Schema = new Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
});

export interface IUser extends Document {
    name: string;
    email: string;
}

export default mongoose.model<IUser>('User', UserModel);

and I try to select some user:

UserModel.findOne({email:data.email}).then((user)=>{
    console.log(user);
    // I get everything without _id
    // { name: "someString", email: "someString" } 
    console.log(user.id);
    // null
});

Another attempt

I've also tried to set _id to false in options:

const UserModel: Schema = new Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
}, { _id: false });

and I tried to select some user:

UserModel.findOne({email:data.email}).then((user)=>{
    console.log(user);
    // I get everything with _id
    // { _id: 10, name: "someString", email: "someString" } 
    console.log(user.id, user._id);
    // but it is not accessible
    // null, undefined
});

Note

If I create document record through mongoose it creates _id as ObjectId() and it is selectable.

1 Answers

Mongoose expects an ObjectID for _id

Add your custom type to the schema

const UserModel: Schema = new Schema({
    _id: { type: mongoose.Schema.Types.Mixed, required: true },
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
});

The _id index can't be modified so don't worry about adding index options.

It's usually best to leave Mongo to use it's ObjectID.

Related