Reputation: 19
I am inserting the documents in mongod db colletion
every time triggerdate and event will change, but if insert them continuously with any time gap we are getting mongo duplication error.
but if we are doing insertion with time back it's getting inserted.
var MongoClient = require('mongodb').MongoClient;
var msgObj = {
"event" : "Password expired",
"assignee" : "Test",
"triggerDate" : "06/21/2018 18:44:27", }
var url ="mongodb://127.0.0.1:27017/org_democustomer"
for( var i=0; i<300;i++){
MongoClient.connect(url, function (err, db) {
var connection = db;
var collection = db.collection('events');
// Insert all customer's tickets into document
collection.insert(msgObj, function (err, result) {
if (err) throw err;
connection.close();
});
});
}
so, how ObjectId creation is? is it based on time? error is
MongoError: E11000 duplicate key error collection: org_mssdemocustomer.testalerts index: id dup key: { : ObjectId('507f191e810c19729de860ea') }
How can I generate unique id for immediate insertions
Upvotes: 1
Views: 117
Reputation: 1341
ObjectId value. The 12-byte ObjectId value consists of:
Here is your code which is working fine.
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID
var msgObj = {
"event": "Password expired",
"assignee": "Test",
"triggerDate": "06/21/2018 18:44:27"
}
var url = "mongodb://127.0.0.1:27017"
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
}
for (var i = 0; i < 300; i++) {
//var connection = db;
//var collection = db.collection('events');
var dbo = db.db("org_democustomer1");
// Insert all customer's tickets into document
msgObj._id = new ObjectID();
dbo.collection("events").insert(msgObj, function(err, result) {
if (err) throw err;
});
}
db.close();
});
Upvotes: 1