得到重复的密钥错误dup key:{:undefined}

时间:2017-12-04 00:33:03

标签: mongodb meteor duplicates unique

我在udids架构中有一个名为Meteor.users的数组字段,该字段应包含唯一元素。这就是我使用SimpleSchemaCollection2定义索引的方法:

new SimpleSchema({
  ...
  udids: {
    type: Array,
    index: true,
    unique: true,
    optional: true,
    sparse: true,
  },
  'udids.$': {
    type: String,
  },
  ...
})

但是,当我启动应用时,我收到了此错误:E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined } 我尝试在数据库中使用udids = undefined搜索文档:db.users.find({ udids: { $type: 6 } })$type: 6undefined值,但它不返回任何内容。

2 个答案:

答案 0 :(得分:0)

我没有对此进行测试,但理想情况下应该可行。

  1. 使用Meteor.users作为集合名称。您可能希望将其替换为要对其运行验证的任何集合。
  2. 利用自定义函数查找至少一个包含udids中字段值的文档。
  3. 如果您无法访问客户端上的集合,则可以编辑自定义函数并对其进行处理asynchronously
  4. new SimpleSchema({
                ...
                'udids': {
                    optional: true,
                    type: [String], // an array of string eg. ['A','B']
                    custom: function() {
    
                        // this.value = current field's value
                        // Below mongo query will check to see if there is at least one 
                        // mongo doc whose udids contains the currently entered field's value.
                        // if found, then return the error message.
    
                        if (Meteor.users.findOne({
                                udids: {
                                    $in: [this.value]
                                }
                            })) {
                            return "duplicateMsg";
                        }
                    },
                    ...
         });
    
    SimpleSchema.messages({ duplicateMsg:"Udid already exists"});
    

答案 1 :(得分:0)

错误信息有点不清楚所以我不得不猜测原因。我发现当前数据库已经有一些用户udids = []。我正在编写一个迁移脚本来取消这些用户的这个字段。希望这能帮助那些和我一样有问题的人。