我的猫鼬模式产生 2 个 objectId 而不是 One ({ "error" : "" _id\ " is not allowed in " 选项\ " " })



这是我的猫鼬模式

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

这是处理架构的服务

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);
}

}

现在每当我点击这个端点时,我都会从邮递员那里收到此错误

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

在我的 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

现在我一直在试图弄清楚为什么我有两个"ObjectId"而不是一个,据我所知,这应该只是一个,我猜是我收到错误的原因这个"{"错误":"_id"不允许在"选项"}"中,或者可能是别的什么。真的会帮助找出问题的根本原因.谢谢

ObjectId只是一个类型,即mongoose.Schema.Types.ObjectId,您可以在文档中拥有任意数量的文档。

_id是唯一的,因为它是该文档的主键,由 Mongo 自动生成。

您在Postman中看到的错误看起来像是来自其他地方。它不能来自服务,因为根据代码的这一部分,那里的错误会被捕获并记录到控制台:

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

我猜错误在更下游,可能是处理return session.toJSON({ virtuals: true });结果的任何东西.

最新更新