无法使用findAndUpdate猫鼬更新架构

时间:2019-11-16 06:52:58

标签: javascript node.js database mongodb mongoose

我在模式中有一个代码: 型号

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'不正确?如果可以的话,有人可以帮助我

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题: 代替这个

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

结果是完美的

相关问题