简体   繁体   中英

How to increment property's value(integer) and update with some restrictions in mongoose?

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:

  • First get if exists the value $set.yourPasswordField which means you hace updated the question in that query.
  • Then, if exists, get the document updated using the same filter
  • And last update the desired field.
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM