简体   繁体   中英

My mongoose schema produces 2 objectId instead of One ({"error": "\"_id\" is not allowed in \"options\""})

So here is my mongoose schema

const SessionSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId,
  ref: 'User', },
valid: { type: Boolean, default: true },
userAgent: {field: {type: String} },},{timestamps: true,},)

And here is the service which handles the schema

const createSession = async (userId, userAgent) => {
try{
    console.log("Create session")
    const session = await SessionModel.create({
        user: userId,
        userAgent: userAgent,
    })
    return session.toJSON({ virtuals: true });
}catch(e){
    console.log(e);
}

}

Now whenever i hit this endpoint, i get this error from postman

{"error": "\"_id\" is not allowed in \"options\""}

And in my mongodb collection i see the following below

    _id:(objectId)62ea5c81fcf787c6a9a1c410
user:(objectId)62e97e244207a3b0c78dbb1f
valid:true
createdAt:2022-08-03T11:31:13.313+00:00
updatedAt:2022-08-03T11:31:13.313+00:00
__v:0

Now i"ve been stock trying to figure out why exactly i've got two "ObjectId" instead of just one as to the best of my knowledge this ought to be just one and i'm guessing is the reason for my getting the error this " {"error": ""_id" is not allowed in "options""} " or maybe it's something else. Would really appreacite some help in figuring out the root cause of the issue. Thanks

ObjectId is just a type, ie mongoose.Schema.Types.ObjectId , and you can have as many as you want in a document.

_id is unique, in that it's the primary key for that document, and is automatically generated by Mongo.

The error you're seeing in Postman looks like it's from elsewhere. It can't be from the service, as the error there would have been caught and logged to console, based on this part of your code:

}catch(e){
    console.log(e);
}

I'm guessing that the error is further downstream, likely whatever is dealing with the results of return session.toJSON({ virtuals: true }); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM