謝謝閱讀。我是新手,正在學習 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"
uj5u.com熱心網友回復:
這是因為貓鼬模式{ timestamps: true }選項,它會updatedAt在更新發生時自動設定欄位。
一種替代方法是管理createdAt和updatedAtbillingProfileSchema手動。
或者只是設定{ timestamps: false }為 billingProfileSchema
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/390980.html
上一篇:如何在反應中更改分頁變數
