Express.js-为每个循环顺序调用三个从属MongoDB查询

时间:2017-09-23 09:22:58

标签: javascript json node.js mongodb express

我必须在MongoDB中插入多个不同的JSON对象,然后检查数据库中是否已存在某些数据,并根据每个JSON对象是否存在数据运行另一个查询。我怎么能在快递中做?我正在使用mongojs包来处理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菜鸟。讨论类似情景的文章链接也很棒。

1 个答案:

答案 0 :(得分:0)

您可以使用异步库来实现此目的。 有两种方法可以做到。

  1. 每次使用async来迭代你的数据,在每个检查数据中首先检查数据是否已经存在,根据查找结果你可以返回或插入文档。
  2. 与1st相同,唯一不同的是你可以使用瀑布进行查找和插入。
  3. 第一种方法:

    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);
       }
    }