Reputation: 135
I am getting this error while trying to insert data in the MongoDB collection.
MongoError: E11000 duplicate key error collection: kaa.logs_96775772132708234336 index: id dup key: { _id: ObjectId('6001bdc2429b9313d755e106') }
Here is my code :
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("kaa");
dbo.collection("logs_96775772132708234336").insertOne(document, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
console.log(res.insertedId);
db.close();
});
});
When I am searching for the same object id, I am getting data. It seems NodejS Mongo is creating a duplicate object ID.
Any help is much appreciated.
Upvotes: 2
Views: 786
Reputation: 153
I had a error like that before and the solution was to delete the collection itself and try again .
Upvotes: 0
Reputation: 89
I do suspect that after insertOn your entity document is reciveng _id filed, which in result casues that you are insrting document with that _id again.
Check your document after inserting it
console.log(document._id);
As in mongo docs
_id Field
If the document does not specify an _id field, then mongod will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.
If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.
Upvotes: 1