I need to enter the multiple record using MongoDB. I am explaining my code below.
var docs=[
{
"zone":"NORTH",
},
{
"zone":"NORTH",
},
{
"zone":"EAST",
},
{
"zone":"EAST",
},
{
"zone":"SOUTH",
},
{
"zone":"SOUTH",
},
{
"zone":"WEST",
}
]
I am inserting the data like below.
var zoneSchema=new Schema({
zone:String
})
var zone = db.model("Zone", zoneSchema);
for(var i=0;i<docs.length;i++){
var datazone={
zone:docs[i]['zone']
}
console.log('zone',docs[i]['zone']);
zone.collection.countDocuments({'zone':docs[i]['zone']},function(err2,zdocs){
if (!err) {
//console.log('zdocs',zdocs);
if (zdocs > 0) {
console.log('zoneif',docs[i]['zone']);
}else{
zone.collection.insert(datazone,function(zerr1,zuse){
if (!zerr1) {
if (zuse) {
var zid=zuse.insertedIds[0];
console.log('z',zid);
//state.collection.find({'zone_id':})
}
}
})
}
}
})
}
Here I am checking the duplicate record and inserting the record but in my case its only inserting the last data of array. Here I need to insert all data from docs
array with checking the duplicate record.