I have a Promise, which I am resolving and then I am iterating through it while saving to a mongo database with mongoose.
I am absolutely sure that I have no duplicates (see output) and I still get the following duplicate key error. It might be related to the promise. The first object gets saved normally, and then it crashes.
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();
}
}
});
});
});
The output is:
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)
What I tried:
- I tried implementing async behaviour, but failed.
- I tried using the default assigned IDs by mongoose instead of mine, but same error
The model:
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);
EDIT
In the mongo database, this gets saved:
{"_id":"515595203781066753","points":{"$numberInt":"0"},"name":"somename","__v":{"$numberInt":"0"}}