【问题标题】:Can not update schema with findAndUpdate mongoose无法使用 findAndUpdate mongoose 更新架构
【发布时间】:2020-03-12 06:34:46
【问题描述】:

我在架构中有一个代码: 型号

const TypeSchema = new Schema({
  title: {
    type: String,
    required: [true, 'Title field is required'],
    minlength: 2,
    maxlength: 128,
    unique: true
  },
  ...
});

然后更新

TypeSchema.pre('findOneAndUpdate', function(next){
  console.log(this.title) // undefined
  this.alt = slug(this.title);
  next();
});

这里我在 this.title 中未定义..

并在 api 中请求:

router.put('/arrivals/products/types/:id', isAuthenticated, async (request, response, next) => {
  jsonPreProcessor.response = response;
  let id = request.params.id;

  let title = request.body.title;

  console.log('router ', title); // title is working
  if (id === undefined) {
    return jsonPreProcessor.error("Id не указан");
  }

  if (title === undefined) {
    return jsonPreProcessor.error("Title не указан");
  }

  Type.findByIdAndUpdate(id, {
    title: title
  }, {
    new: true
  }).then(type => {
    return jsonPreProcessor.success(type);
  }).catch(error => {
    return jsonPreProcessor.error(error.message); // here I got an error message that title is undefined (in pre.('findOneAndUpdate'))
  });
});

但这里我通常有一个标题

也许我使用 pre 'findOneAndUpdate' 不正确?如果可以的话,谁能帮帮我

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    我已经解决了我的问题: 而不是这个

    TypeSchema.pre('findOneAndUpdate', function(next){
      console.log(this.title) // undefined
      this.alt = slug(this.title);
      next();
    });
    

    我写了

    TypeSchema.pre('findOneAndUpdate', function(next){
      this.update({
        $set: {
          alt: slug(this.getUpdate().title)
        }
      });
      next();
    });
    

    结果很完美

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多