【问题标题】:Node.js Mongoose duplicate key when entering the same UserName输入相同用户名时的Node.js Mongoose重复键
【发布时间】:2016-06-09 23:38:57
【问题描述】:

在我的 MongoDb 数据库中,用户配置文件集合遵循此架构:

{
"_id": {
    "$oid": "566c69ab266ee48f24105a31"
},
"userid": "8d67e890-a0ff-11e5-9203-93a5a9af8b67",
"telnumber": {
    "value": "0600000000",
    "share": true
},
"fullname": {
    "value": "Oscar Götting",
    "share": true
},
"emailaddr": {
    "value": "x@y.fr",
    "share": true
},
"__v": 0

}

为了在 node.js 中重现此 Schema,我正在执行以下代码:

 // Profile fields schema
var yokiProfileDataField = new mongoose.Schema({
  value: String,
  share: Boolean
},{ _id : false });

// Profile data schema
var yokiProfileDataSchema = new mongoose.Schema({
  userid: { type: String, required: true, unique: true }, // User unique user-id
  emailaddr: { type: yokiProfileDataField },
  fullname: { type: yokiProfileDataField },
  telnumber: { type: yokiProfileDataField }
});

如果我尝试使用其他人已经输入的名称进行注册,我会收到重复密钥错误:

MongoError: E11000 duplicate key error index: yoki_users.profiles.$fullname_1 dup key: { : { value: "Oscar Götting", share: true } }
    at Function.MongoError.create (/Users/Rakso/Projets/Yoki/YokiWeb/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
    at toError (/Users/Rakso/Projets/Yoki/YokiWeb/node_modules/mongoose/node_modules/mongodb/lib/utils.js:114:22)
    at /Users/Rakso/Projets/Yoki/YokiWeb/node_modules/mongoose/node_modules/mongodb/lib/collection.js:597:23
    at /Users/Rakso/Projets/Yoki/YokiWeb/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:469:9
    at resultHandler (/Users/Rakso/Projets/Yoki/YokiWeb/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:416:5)
...

这怎么可能,我该如何解决这个问题? 同样在 MongoLab 中,所有索引的 unique 属性都设置为unique: true,除了在我的代码中设置为unique: false 的那些,是否正常?会不会是问题?

【问题讨论】:

  • 你试过删除有问题的索引吗?
  • 这些索引是我要插入的索引,所以是的,我尝试删除它们,然后将它们重新添加...

标签: javascript node.js mongodb mongodb-query


【解决方案1】:

我刷新了所有索引并开始使用新索引。它解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多