【发布时间】: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