![](/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.