简体   繁体   English

如何在 mongoose 中增加属性值(整数)和更新?

[英]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.我有一个 studentSchema,其中有默认值为 0 的 pass 属性。所以我想在用户创建新 pass 时将该值增加 1。

 pass: {
  type: Number,
  default: 0,
},

If I've understand you correctly, you can use mongoose pre hook in this way:如果我对您的理解正确,您可以通过这种方式使用 mongoose预挂钩

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.首先获取值$set.yourPasswordField是否存在,这意味着您已经更新了该查询中的问题。
  • 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()
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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