【发布时间】: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