【发布时间】:2018-09-23 04:06:36
【问题描述】:
我目前有以下架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Comments = new Schema({
authorId: {
type: Schema.Types.ObjectId,
unique: false
},
commentBody: {
type: String
}
});
//Create schema
const GroupSchema = new Schema({
name:{
type: String,
required: true
},
comments: [Comments]
});
module.exports = Group = mongoose.model('group', GroupSchema);
我可以毫无错误地插入第一组,但是当我尝试添加第二组时,我得到了这个错误:
{
"error": {
"name": "MongoError",
"message": "E11000 duplicate key error collection: app-idiomas.groups index: comments.authorId_1 dup key: { : null }",
"driver": true,
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: app-idiomas.groups index: comments.authorId_1 dup key: { : null }"
}
}
所以,我想,问题出在“评论”模式上,我已经搜索了嵌套模式,看看我是否能解决这个问题。我曾尝试使用“默认”和“稀疏”属性,但没有成功。
最后我决定做一个测试并删除评论模式,它在组模式中的引用只是为了确认一切正常。我删除了所有数据库并添加了第一组(现在没有任何 cmets 属性),但每当我尝试添加第二组时,我仍然会收到错误消息。我只是不知道为什么。
有什么帮助吗?
更新
这几天没时间,终于找到问题所在了。可能当我创建 Comments Schema 时,我可能将 authorId 设置为唯一的,因此 MongoDB 为该属性创建了一个索引。我对 MongoDB 了解不多,这就是我以前没有检查过的原因。但这里是我找到索引并删除它的地方:
【问题讨论】: