使用“异步”库将数据插入数据库时​​,如何避免重复记录

时间:2018-12-27 10:54:14

标签: node.js mongodb

const obj =[
        {userName:'a',firstName:'kote',lastName:'perumalla  '},
        {userName:'a',firstName:'kote',lastName:'perumalla  '},
        {userName:'as',firstName:'koteswararaO',lastName:'perumalla'},
        {userName:'as',firstName:'koteswararaoH',lastName:'perumalla'},
         ];
     async.each(obj,function(item,callback){
        MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
      const DaTa = db.db("mydb"); 
         const asa =item.userName;    DaTa.collection("Campus").find({userName:item.userName}).toArray(function(err, result) {
        if(result.length <=0){
            DaTa.collection("Campus").insertMany(obj,function(err,result){ 
                if(result){
                  return   callback();
                }
                    })
                  }   
        else{
            DaTa.collection("Campus").updateOne({userName:item.userName},{$set:{"firstName":item.firstName}},function(er,result){
                console.log(result +'1 record is updated')
                if(result){
                   return  callback();
                }
                })
            }
        db.close();
        callback('Done');
            })
     });
     },function(err,result){
        console.log('completed')
     })

我在Node.js中使用.each包的async方法。我想避免将重复的记录插入到MongoDB数据库中。

请告诉我应该更改代码的哪一部分以实现异步插入唯一记录。

2 个答案:

答案 0 :(得分:0)

您可以在MongoDB中定义唯一索引。

db.collectionName.createIndex( { "userName": 1 }, { unique: true } );

答案 1 :(得分:0)

var DaTa;
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
    DaTa = db.db("mydb");
    async.eachSeries(obj,function(item,callback){
        console.log("*****************************")
        const asa =item.userName;
        // DaTa.createIndex( { "_id": 1 }, { unique: true } );
        console.log("item: ",item)
        DaTa.collection("Campus").find({userName:item.userName}).toArray(function(err, result) {
            console.log(result.length)
            console.log("result: ", result)
            if(result.length <=0){
                console.log("doc not found")
                DaTa.collection("Campus").insert(item,function(err,result){

                    if(result){
                        callback();
                    }
                })
            }else{
                console.log("doc found")
                DaTa.collection("Campus").update({userName:item.userName},{$set:{"firstName":item.firstName}},function(er,result){
                    // console.log(result +'1 record is updated')
                    console.log("doc update result: ",result.result)
                    if(result) {
                        callback();
                    } 
                })
            }
        })
    }, function(err,result){
        console.log('############ completed ##################')
    })
  // db.close()
 });