E11000重复密钥,猫鼬中没有重复密钥

时间:2020-09-25 14:45:17

标签: javascript node.js mongodb mongoose

我有一个Promise,我正在解决这个问题,然后遍历它,同时用mongoose保存到mongo数据库中。

我绝对确定没有重复项(请参见输出),并且仍然出现以下重复项错误。这可能与承诺有关。第一个对象正常保存,然后崩溃。

Promise.resolve(members).then(function(value){
    value.forEach(member => {
        Player.findById(member['id'], function(err, foundPlayer){
            if (err){
                console.log(err);
                return;
            }else{
                if(foundPlayer) console.log(member['id'] + ' already registered.');
                else{
                    console.log('saving with id ' + member['id']);
                    new Player({name: member['nickname'], _id: member['id']}).save();
                } 
            }
        });
    });
});

输出为:

saving with id 515595203781066753
saving with id 725997594014384139
saving with id 740967607624269855
(node:29052) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: users.players index: id_1 dup key: { id: null }
...
(node:29052) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
...
(node:14580) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:14580) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: users.players index: id_1 dup key: { id: null }
...
(node:14580) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

我尝试过的事情:

  • 我尝试实现异步行为,但失败了。
  • 我尝试使用猫鼬而不是我的默认分配的ID,但存在相同的错误

模型:

var mongoose    = require('mongoose');

var PlayerSchema = new mongoose.Schema({
     _id: {type: String},
     name: String,
     points: {type: Number, default: 0}
});

module.exports = mongoose.model("Player", PlayerSchema);

编辑

在mongo数据库中,将保存以下内容:

{"_id":"515595203781066753","points":{"$numberInt":"0"},"name":"somename","__v":{"$numberInt":"0"}}

1 个答案:

答案 0 :(得分:0)

根据错误消息,在名为id的字段上存在唯一索引。

index: id_1 dup key: { id: null }

在保存呼叫中,您正在设置_id,而不是id

new Player({name: member['nickname'], _id: member['id']}).save();

构建索引条目时,MongoDB用null表示缺少的字段。

save()函数返回一个Promise,因此很可能您在返回第一个错误之前已经到达了第3个或第4个文档。