![](/img/trans.png)
[英]How to specify the _id field with Mongoose when creating a document in MongoDB?
[英]mongoose: Cannot specify a custom index on `_id` for model name "SchemaName", MongoDB does not allow overwriting the default `_id` index
所以我只是嘗試在 mongoose 模式中自定義_id
,如下所示:
const userSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
unique: true
},
...
...
})
並收到此消息: mongoose: Cannot specify a custom index on _id for model name "SchemaName", MongoDB does not allow overwriting the default _id index.
問題是,一切都很好。 我可以像往常一樣插入數據和 select 。 我應該對該消息做些什么嗎?
我認為當您嘗試定義required:true
和unqiue:true
時出現錯誤,因為_id
已經有了這個,也就是說,即使 mongoose 的條件不存在,您也不能讓_id
具有非 unqiue 值它總是需要的。 嘗試刪除這兩個約束並僅設置type:String
並且此消息應該消失
將_id: false
添加到 options ,{}
(第二個參數)可以解決問題:
const userSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
}, { _id: false })
這告訴 Mongo 你不希望_id
由 Mongo/Mongoose 自動創建。 因為你想自己做,用自己的方式。
事實上,如果你不使用_id
,你甚至不需要在第一個參數中提及它。 只有第二個很重要({ _id: false }):
const userSchema = new mongoose.Schema({
code: { type: String, required: true, unique: true },
name: { type: String, required: true },
another: { type: Number, required: false },
}, { _id: false })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.