更新数组Mongoose中的嵌套对象

时间:2020-07-15 13:10:58

标签: node.js mongodb express mongoose

我希望更新ID为5f0e14241f5ccb42d8742767的嵌套对象:

 {
        "_id": "5f0b33ab52a4e966c754d963",
        "make": "Toyota",
        "model": "Prius",
        "engine": "1.8",
        "insurances": [
            {
                "yearlyPremium": {
                    "$numberDecimal": "60.39"
                },
                "_id": "5f0e14241f5ccb42d8742767",
                "startDate": "1970-01-19T09:31:15.550Z",
                "monthlyPremium": {
                    "$numberDecimal": "5.49"
                },
                "excess": 100
            },
            {
                "yearlyPremium": {
                    "$numberDecimal": "71.39"
                },
                "_id": "5f0e147c0340243eb03b5247",
                "startDate": "1970-01-19T09:31:15.550Z",
                "monthlyPremium": {
                    "$numberDecimal": "6.49"
                },
                "excess": 100
            },
       ]
 }

因此,在我的PATCH rest api请求中,我只想将每月保费从当前的5.49更改为1.50。因此,我将carId: 5f0b33ab52a4e966c754d963和特定的inusranceId: 5f0e14241f5ccb42d8742767(嵌套在Car对象中)传递为查询参数,以标识Insurances数组中的哪些保险需要更新。然后在请求正文中传递要修改的项目(monthlyPremium

enter image description here

我遵循了堆栈溢出解决方案:mongoDB: Update nested array object

这就是我尝试过的:

router.route('/insurance')
.patch(async (req, res) => {
    const { carId, insuranceId } = req.query
    const { startDate, monthlyPremium, excess } = req.body
    try {
        const foundCar = await Car.findById(carId)
        const foundCar = foundCar.insurances.filter(ins => {
            return ins._id == insuranceId
        })
        
        foundInsurance.startDate = startDate && new Date(startDate * 1000) || foundInsurance.startDate,
        foundInsurance.monthlyPremium = monthlyPremium && parseFloat(monthlyPremium) || foundInsurance.monthlyPremium,
        foundInsurance.yearlyPremium = monthlyPremium && parseFloat(monthlyPremium) * 12 || foundInsurance.yearlyPremium,
        foundInsurance.excess = excess && Number(excess) || foundInsurance.excess
        
        Car.update(
            {_id: carId, "insurances._id": insuranceId}, 
            {$set: {"insurances.$":foundInsurance}}
        )

        res.send(`Insurance updated`)
    } catch (err) {
        res.status(400).json({ error: err })
    }
})

在代码中正确捕获了请求查询。该请求成功并返回Insurance updated,但没有任何更新。一切正常,但更新方法未将信息monthlyPremium更新为1.50

更新

@Mahan,我尝试了您建议的方法,但是,记录仍然没有改变。打印foundInsurance,我明白了(它不会打印控制台中的值,仅打印元数据):

found insurance: {
  yearlyPremium: Decimal128 {
    _bsontype: 'Decimal128',
    bytes: <Buffer 97 17 00 00 00 00 00 00 00 00 00 00 00 00 3c 30>
  },
  _id: 5f0e14241f5ccb42d8742767,
  startDate: 1970-01-19T09:31:15.550Z,
  monthlyPremium: Decimal128 {
    _bsontype: 'Decimal128',
    bytes: <Buffer 25 02 00 00 00 00 00 00 00 00 00 00 00 00 3c 30>
  },
  excess: 100
}

1 个答案:

答案 0 :(得分:0)

请尝试像这样使用猫鼬arrayFilters

Car.update(
  { _id: carId }, 
  { $set: { "insurances.$[elem]": foundInsurance } },
  { arrayFilters: [ { 'elem._id': insuranceId } ] }
)