【问题标题】:Mongoose duplicate key error in nested schema嵌套模式中的猫鼬重复键错误
【发布时间】: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 了解不多,这就是我以前没有检查过的原因。但这里是我找到索引并删除它的地方:

Location of "indexes" tab in MongoDB

【问题讨论】:

    标签: database mongodb mongoose


    【解决方案1】:

    这个问题应该是数据库中的记录。
    但是正如您所说,您清除了数据库,问题看起来很奇怪。
    只需再次检查您是否删除了正确的数据库,即您在 api 中使用的数据库。

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 2015-09-09
      • 2019-03-22
      • 2015-09-21
      • 2018-10-09
      • 1970-01-01
      • 2014-06-22
      • 2019-01-16
      • 2017-01-28
      相关资源
      最近更新 更多