【问题标题】:Express.js- Calling three Dependent MongoDB queries sequentially for each loopExpress.js- 为每个循环顺序调用三个 Dependent MongoDB 查询
【发布时间】:2017-09-23 09:22:57
【问题描述】:

我必须在 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 菜鸟。讨论类似情况的文章链接也很好。

【问题讨论】:

  • 这应该用瀑布方法修复。你能把你的 async.waterfall 代码和你运行它时遇到的错误放在这里吗?
  • 我遵循了下页中给出的示例:codeforgeek.com/2016/04/asynchronous-programming-in-node-js 除了在函数之前我添加了 db.carddata.insert() 等等,就像我在前面的代码中所做的那样。

标签: javascript json node.js mongodb express


【解决方案1】:

您可以使用异步库来实现这一点。 有两种方法可以做到。

  1. 使用 async each 来迭代您的数据,并在每个检查数据中首先检查数据是否已经存在,根据查找结果您可以返回或插入文档。
  2. 和第一种一样,唯一不同的是你只能使用瀑布来查找和插入。

第一种方法:

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

【讨论】:

  • 非常感谢!
  • 但解决方案不起作用。无论如何,再次感谢您的尝试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多