I have a studentSchema in which there are pass property with default value 0. So I want to increse that value by 1 when user creates new pass.
pass: {
type: Number,
default: 0,
},
If I've understand you correctly, you can use mongoose pre hook in this way:
Assuming you are updating in this way (or similar):
model.update({_id:value},{$set:{yourPasswordField:"newName"}})
Then you need:
$set.yourPasswordField
which means you hace updated the question in that query.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()
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.