![](/img/trans.png)
[英]Unable to update a document's property value which is in an array of objects in Mongoose
[英]How to increment property's value(integer) and update with some restrictions in mongoose?
我有一個 studentSchema,其中有默認值為 0 的 pass 屬性。所以我想在用戶創建新 pass 時將該值增加 1。
pass: {
type: Number,
default: 0,
},
如果我對您的理解正確,您可以通過這種方式使用 mongoose預掛鈎:
假設您以這種方式(或類似方式)更新:
model.update({_id:value},{$set:{yourPasswordField:"newName"}})
那么你需要:
$set.yourPasswordField
是否存在,這意味着您已經更新了該查詢中的問題。MongooseModel.pre('update', async function () {
// get the fields which have been updated.
const passUpdated = this.getUpdate().$set.yourPasswordField;
if(passUpdated){
// Find the object using the filter in your query (i,e: {_id:value} )
const docToUpdate = await this.model.findOne(this.getFilter());
// Then update the value into 1 and save into DB
docToUpdate.pass = docToUpdate.pass + 1;
docToUpdate.save()
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.