$ set更新嵌套字段会覆盖数据

时间:2018-11-22 09:22:04

标签: node.js mongodb mongoose

这是我的猫鼬模型。

var orderSchema = Schema({
    order_id:  {type:String, index:true, required:true, unique:true},
    payment: {
       type: {type: String},  
       total_fee: {type:Number, default:0},
       openid: {type: String},
       transaction_id: {type: String}, 
       status: {type:String,default:"UNPAID"}
    }
});

我最初创建了订单,结果将数据保存在mongodb中,如图所示

{
    "order_id" : "order_2018111541812723",
    "payment" : {
        "total_fee" : 0.01,
        "type" : "wechat",
        "openid" : "oFPE65EVQEt44Dgvv2lFJdT3PQtQ",
        "status" : "UNPAID"
    }
}

然后我尝试使用下面的代码更新订单

  const query = {"order_id": "order_2018111541812723"};  
  const update = { '$set': {"payment":{"status":"SUCCESS","transaction_id":"FJdT3PQtQt44Dgvv2oFPE65EVQ"}} };
  collection.findOneAndUpdate(query,update,{new:true, upsert:true}, getResult);

现在结果已更新,但是付款中的某些数据字段(如openid,类型)也丢失了。

{
    "order_id" : "order_2018111541812723",
    "payment" : {
        "transaction_id" : "FJdT3PQtQt44Dgvv2oFPE65EVQ",
        "status" : "UPAID"
    }
}

我该如何解决问题?

0 个答案:

没有答案