简体   繁体   English

我的 mongoose 架构产生 2 个 objectId 而不是一个({"error": "\"_id\" is not allowed in \"options\""})

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

So here is my mongoose schema所以这是我的 mongoose 架构

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现在每当我点击这个端点时,我都会从 postman 收到这个错误

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

And in my mongodb collection i see the following below在我的 mongodb 收藏中,我看到以下内容

    _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”而不是一个,据我所知,这应该只是一个,我猜是我得到错误的原因这个“ {”error”:“options”}中不允许“_id”或者它可能是别的东西。真的会帮助找出问题的根本原因。谢谢

ObjectId is just a type, ie mongoose.Schema.Types.ObjectId , and you can have as many as you want in a document. ObjectId只是一种类型,即mongoose.Schema.Types.ObjectId ,您可以在文档中拥有任意数量的类型。

_id is unique, in that it's the primary key for that document, and is automatically generated by Mongo. _id是唯一的,因为它是该文档的主键,并且由 Mongo 自动生成。

The error you're seeing in Postman looks like it's from elsewhere.您在 Postman 中看到的错误看起来像是来自其他地方。 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 });我猜该错误在更下游,可能是在处理return session.toJSON({ virtuals: true });的结果。 . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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