【问题标题】:How to increment property's value(integer) and update with some restrictions in mongoose?如何增加属性的值(整数)并在猫鼬中使用一些限制进行更新?
【发布时间】:2021-01-07 07:38:04
【问题描述】:

我有一个 studentSchema,其中有默认值为 0 的 pass 属性。所以我想在用户创建新通行证时将该值增加 1。

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    如果我没听错的话,你可以这样使用猫鼬pre hook

    假设您以这种方式(或类似方式)更新:

    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()
      }
    });
    

    【讨论】:

    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多