簡體   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\""})

所以這是我的 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,},)

這是處理模式的服務

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

}

現在每當我點擊這個端點時,我都會從 postman 收到這個錯誤

{"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”而不是一個,據我所知,這應該只是一個,我猜是我得到錯誤的原因這個“ {”error”:“options”}中不允許“_id”或者它可能是別的東西。真的會幫助找出問題的根本原因。謝謝

ObjectId只是一種類型,即mongoose.Schema.Types.ObjectId ,您可以在文檔中擁有任意數量的類型。

_id是唯一的,因為它是該文檔的主鍵,並且由 Mongo 自動生成。

您在 Postman 中看到的錯誤看起來像是來自其他地方。 它不能來自服務,因為根據您的代碼的這一部分,那里的錯誤會被捕獲並記錄到控制台:

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

我猜該錯誤在更下游,可能是在處理return session.toJSON({ virtuals: true });的結果。 .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM