以下是我的努力:
async.waterfall([
function(nextCall){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const dbo = db.db("testmdb");
const criteria = {"_id":ObjectId(id)};
console.log("paymentInof[] ::: ",paymentInfo)
let obj = paymentInfo[0];
const query = {
$push:{payment:obj}
};
dbo.collection("Invoice").update(criteria, query);
db.close();
nextCall(null,{code:200});
});
}
],function(err,results){
if(err) return err;
if(results.code === 200)
console.log(chalk.blue(' ::: all done ::: '));
next();
});
来自api explorer的输入:
{
"payment":[{"transaction_at":"2018-02-12T06:04:35.279Z","paid_amount":350,"patient_id":"1233sssdd33","patient_urn":"214125","invoice_amount":700,"user":"me"}],
"updated_by": "me"
}
一切正常但无法推送覆盖支付数组中的现有对象。
从mongo shell开始,它工作正常。
请帮助我,我做错了什么?
感谢。
答案 0 :(得分:0)
我认为您需要检查mongoose update
upsert
选项。
更新选项
有几个选项值可用于更新
multi
- 更新与查询对象匹配的所有记录,默认为false(仅查找找到的第一个记录)
upsert
- 如果为true且没有记录与查询匹配,请将update作为新记录插入
raw
- 驱动程序将更新的文档作为bson binary Buffer返回,默认值为false
请查看文档here。
使用以下代码
async.waterfall([
function(nextCall){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const dbo = db.db("testmdb");
let criteria = {"_id": ObjectId(id)};
let obj = paymentInfo[0];
let query = { $push: { payment: obj } }
dbo.collection("Invoice").update(criteria, query, {upsert:true});
db.close();
nextCall(null,{code:200});
});
}
],function(err,results){
if(err) return err;
if(results.code === 200)
console.log(chalk.blue(' ::: all done ::: '));
next();
});
希望这会对你有所帮助!!