2017-09-23 5 views
0

MongoDBに複数の異なるJSONオブジェクトを挿入し、データの一部が既にデータベースに存在するかどうかをチェックし、各JSONオブジェクトについてはそうではありません。 expressjsで私はどうすればいいですか?私はMongoDBを使ってmongojsパッケージを使用しています。私が入力したコードは以下の通りです:Express.js-ループごとに3つの依存MongoDBクエリを順番に呼び出す

app.post('/addcard/:id', function(req, res) { 
console.log("Received Add Card Request"); 
var date = new Date(); 
var year = date.getFullYear(); 
var month = date.getMonth(); 
var day = date.getDate(); 
var yrval = req.body.yrval; 
var monval = req.body.monval; 
var dateval = req.body.dateval; 

for (var i=0;i<req.body.phone.length;i++){ 
    //console.log(i); 
    var card = new Card({ 

    cardType     : req.body.cardtype, 
    cardTitle     : req.body.cardtitle, 
    allowMultipleStore   : false, 
    phoneNumber     : req.body.phone[i], 
    messageUser     : req.body.message, 
    expiryDate     : new Date(year+yrval,month+monval,day+dateval), 
    creditPoints    : req.body.creditpoints, 
    punchCount     : req.body.punch, 
    messageReachPunchLimit  : req.body.limitmessage, 
    merchantUsersId    : mongoose.Types.ObjectId(req.body.merchantuserid), 
    merchantId     : mongoose.Types.ObjectId(req.params.id) 
    }); 
console.log(card); 
    db.carddata.insert(card, function (err,docInserted){ 

    // console.log(card); 
    console.log(i); 
    if (err) throw err; 

    db.userdata.find({phoneNumber:req.body.phone},function (err,docs){ 
     console.log("hiss"); 
     if (err) throw err; 

     if (docs.length!=0){ 
     var carduser = new CardUsersAssignment({ 

    cardId       : docInserted._id, 
    userId       : docs[0]._id, 
    remainingCreditPoints    : req.body.creditpoints, 
    remainingPunchCount    : req.body.punch 
    }); 
     db.carduser.insert(carduser,function (err){ 

     console.log(" Card Details saved successfully_existing"); 
     //console.log(i); 



     }) 

     }//If (docs.length!=0) 
     else{ 

    console.log(" Card Details saved successfully"); 

} 


    })//Finding by PhoneNumber 
    console.log(i+1); 


})//Insert Function 
console.log("hi"); 

} // End of For Loop 
res.json({ 
    success:true, 
    message:"Hello. You did it!" 
}); 

}); 

このコードは、私が逐次実行のために書いていたかのように書かれています。私はNodeJSが非同期であることを知っています。 async.waterfallを試しましたが、mongodbクエリ関数でエラーが発生しています。どんな助けも素晴らしいだろう。私はNodeJS noobです。同様のシナリオについて議論する記事へのリンクも素晴らしいでしょう。

+0

これは滝の方法で固定されなければなりません。 async.waterfallコードをここに入れて、実行時にエラーが出ることはありますか? –

+0

私は以下のページで与えられた例に従っています: https://codeforgeek.com/2016/04/asynchronous-programming-in-node-js/ 機能を除いて、db.carddata.insert()を追加しました。前のコードでやったように。 –

答えて

0

これは非同期ライブラリを使用して実現できます。 これには2通りの方法があります。

  1. asyncを使用してデータを繰り返し処理し、各チェックデータの中に最初にチェックデータが存在するかどうかは、結果を元に返すか挿入することができます。
  2. これは1stと同じですが、唯一違うのは、検索と挿入に滝を使用できることです。

最初のアプローチ:

async.each(req.body.phone, function(data, callback) { 
    // Create card Info 
    db.carddata.insert(card, function (err,docInserted){ 
    if (err) {throw err;} 
    db.userdata.find({phoneNumber:req.body.phone},function (err,docs){ 
     if (err) {throw err; 
     } else if (docs.length){ 
     // create carduser data 
     db.carduser.insert(carduser,function (err){ 
      if (err) {throw err;} 
      callback();   
     } 
     } else { 
     console.log(" Card Details saved successfully"); 
     callback(); 
     } 

    } 
}, function(err) { 
    // if any of the file processing produced an error, err would equal that error 
    if(err) { 
    // One of the iterations produced an error. 
    // All processing will now stop. 
    console.log('A file failed to process'); 
    } else { 
    console.log('All files have been processed successfully'); 
    } 
}); 

第二のアプローチ:

async.each(req.body.phone, function(data, callback) { 
    //create card data 
    let data = {} 
    data.phone = req.body.phone; 
    data.docInserted = data.docInserted; 
    data.cardata = cardData; 
    async.waterfall([ 
    insertCard, 
    updateDataFind, 
    cardDataInsert, 
    async.apply('insertCard', data) 
    ], function (err, result) { 
    if(err){ 
     if(err.success){ 
     callback(); 
     } 
     throw err; 
    } 
    callback(); 
    }); 
}, function(err) { 
    // if any of the file processing produced an error, err would equal that error 
    if(err) { 
    // One of the iterations produced an error. 
    // All processing will now stop. 
    console.log('A file failed to process'); 
    } else { 
    console.log('All files have been processed successfully'); 
    } 
}); 
function insertCard(data, callback){ 
    db.carddata.insert(card, function (err,data.docInserted){ 
    if(err){throw err;} 
    callback(null, data); 
    } 
} 
function updateDataFind(data, callback){ 
    db.userdata.find({phoneNumber:data.phone},function (err,docs){ 
    if (err) {throw err;} 
    else if (docs.length!=0){ callback(null, data); } 
    else { callback({success:true}) } 
    } 
} 
function cardDataInsert(data, callback){ 
    // create card user or pass from data. 
    db.carduser.insert(carduser,function (err){ 
    if (err) {throw err;} 
    callback(null, data); 
    } 
} 
+0

ありがとうございました! –

+0

しかし、解決策は機能していません。とにかく、もう一度お試しいただきありがとうございます。 –

関連する問題