【问题标题】:update nested object in array Mongoose更新数组 Mongoose 中的嵌套对象
【发布时间】:2020-07-15 23:14:14
【问题描述】:

我希望更新 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 对象中)作为查询参数传递,以确定保险数组中的哪个保险需要更新。然后在请求正文中传递要修改的项目(monthlyPremium):

我跟着栈溢出解决方法: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
}

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    请尝试像这样使用猫鼬arrayFilters

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

    【讨论】:

    • 谢谢马汉。实际上,现在我在该端点的 POSTMAN 上遇到错误。 { "error": { "stringValue": "\"insurance\"", "kind": "ObjectId", "value": "insurance", "path": "_id", "reason": {} } } 不知道为什么。这与您在我对 POSTMAN 的问题中的屏幕截图中看到的设置相同
    • 请您发布您的foundInsurance 对象好吗?在你设置它的属性之后。
    • 好的,现在问题出在 PATCH 端点上。即使我从任何代码中清空整个回调(对于 API),我仍然会收到此错误。所以端点一定有问题。我看不出问题出在哪里!!!
    • 你是否在你的 express app.js 中设置了app.use(bodyParser.json()); 中间件?
    • 还有app.use(bodyParser.urlencoded({extended: false}));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多