Home:ALL Converter>Could not enter multiple record using MongoDB

Could not enter multiple record using MongoDB

Ask Time:2019-01-18T21:15:27         Author:user5443928

Json Formatter

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.

Author:user5443928,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54254802/could-not-enter-multiple-record-using-mongodb
yy