基本上,我正在使用与mongodb的环回,并希望推送数据,设置数据并将数据增加到一起并获得最终结果。
为此,我尝试了这个。
db.invoice.findOneAndUpdate({ _id: ObjectId(req.params.id) },
{
$push: { payment: paymentData }
, $set: { payment_status: true, updated_at: new Date() }
, $inc: { total_amount_paid: paidAmt }
}
,
function (err, doc) {
if (err) { return new Error(err); }
else {
if (doc.result.n>0) {
setTimeout(function () { }, 200);
console.log(" Invoice updated with Payment info.");
nextCall(null, { code: 200, data: doc.result });
} else {
console.log("Something went wrong while payment info updation.")
nextCall(null, { code: 400, status: 'Something went wrong while payment info updation.' })
}
}
});
});
案例1:
文档正在更新,但没有推送支付数组。
案例2:
如果我删除了回调函数 它正在推动,设定价值并增加支付的总金额。$ inc
如果想要实现case2,有人可以告诉我我在哪里做错了吗?
由于
答案 0 :(得分:0)
一起执行$push, $inc
操作
查找查询:
db.getCollection('noti').find({})
结果:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 8.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 6.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 8.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 8.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 9.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0,
"views" : 1.0
}
更新查询:
db.getCollection('noti').findOneAndUpdate(
{ _id: ObjectId("5bc061f05a4c0511a9252e88") },
{ $push: {
graph: {
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 10.0
}
},
$inc: { count: 1 }
}, {new: true })
结果:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 9.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 6.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 8.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 8.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 9.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 10.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0,
"views" : 1.0
}
此处的计数增加1,并将新的JSON对象插入到图形数组中。