【发布时间】:2022-01-22 01:04:52
【问题描述】:
感谢阅读。我是新手,正在学习 mongoose,并试图围绕子文档更新。我可以更新子文档,但我使用的方法似乎不能很好地扩展并且设置起来很麻烦,但它确实有效。我不想逐个字段更新,即城市、州、邮编、国家等。我想简单地替换已自动更新的字段。
// Sample Object
{
addressType: 'home',
street: '123 Easy Street',
city: 'Somewhere',
state: 'NA',
zip: '90210',
country: 'USA'
}
// Schema
const userSchema = mongoose.Schema({billingProfile: [billingProfileSchema], orders: [orderSchema]}, {timestamps: true, strict: false})
// Updating item by item works, BUT doesn't scale
const billingProfile = await User.findOneAndUpdate({_id:req.user._id, "billingProfile._id":req.params.billingProfileID}, {$set: {"billingProfile.$.city" : req.body.city}}, {new:true})
我在逻辑上想要的是以下内容,但它会导致错误...
// Setting req.body equal to ".$" results in an error
const billingProfile = await User.findOneAndUpdate({_id:req.user._id, "billingProfile._id":req.params.billingProfileID}, {$set: {"billingProfile.$" : req.body}}, {new:true})
Updating the path 'billingProfile.$.updatedAt' would create a conflict at 'billingProfile.$'
我认为应该可行的方法显然行不通。我希望有人可以帮助我以更有效的方式更新子文档。谢谢你:)
仅供参考 - 我正在使用"mongoose": "^6.1.1"
【问题讨论】: