【问题标题】:Mongoose pre hook or method not working with findOneAndUpdate MethodMongoose 预钩子或方法不适用于 findOneAndUpdate 方法
【发布时间】:2016-01-19 03:15:01
【问题描述】:

我正在尝试实现一个递增计数器。我将数字存储在“项目”集合中,并在“问题”集合中插入新文档时尝试检索并增加 1。

我已经尝试了几种不同的方法,但都没有成功。我可以通过简单地获取数字并将其增加 1 并将其与表单提交一起发送来轻松实现这一点,但是我不会学习。从我看到的其他一些答案来看,问题出现在中间件不知道 findOneAndUpdate 查询操作上的文档。

这是我尝试的第一个 .pre 操作,但没有成功。

.pre('save', function(next) {
 counter = Project.findOneAndUpdate({_id: this.project}, {$inc: { numberSeq: 1} });
 console.log(counter);
 this.number = counter.numberSeq;
 next();
});

接下来,我试了一下。控制台输出似乎一切正常,除了文档更新。

.pre('save', function(next){
  console.log('attempting to get next num ');
  Project.findOneAndUpdate({_id: this.project}, {$inc: { numberSeq: 1} }, function(error, counter)   {
    console.log('project is ' + counter.project);
    console.log('number seq is ' + counter.numberSeq);
    this.number = counter.numberSeq;
    console.log('next num sequence is: ' + this.number);
      next();
  });

});

最后,这是我尝试使用的方法。

IssueSchema.methods.getNextNumber = function(project) {
    Project.findOneAndUpdate({_id: project}, {$inc: { numberSeq: 1} }, function(error, counter)   {
        if(error) {
            return error;
          }
          console.log(counter.numberSeq);
        return counter.numberSeq;
    });
};

并像这样使用。它几乎可以工作,但更新似乎在方法提供下一个数字之前完成,并且数字最终未定义。我尝试了几种方法使其同步,但无济于事

    var issue = new Issues({
      title: req.body.title,
      description: req.body.description,
      fields: req.body.fields,
      project: req.body.project,
      created_by: req.user || req.body.created_by,
      type: req.body.type,

    });

    issue.number = issue.getNextNumber();

    issue.save(function(err, result) {
      if (err) {
        return res.status(409).send({message: 'There was an error creating the issue: ' + err});
      }
      console.log(result);
      res.send({message: 'New issue created', result: result});
    });
  });

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    我一直在墙上扔飞镖,直到有东西卡住了。事实证明这很简单,我只需要在回调中分配数字,然后抛出下一个。

    .pre('save', function(next) {
      Project.findOne({_id: this.project}).select('numberSeq').exec(function(err, doc) {
        if (err) {
          console.log(err);
        }
          this.number = doc.numberSeq;
          next();
        });
    })
    .post('save', function(doc) {
      Project.update({_id: doc.project}, {$inc:  {numberSeq: 1}}, function(err, result) {
        if (err) {
          console.log(err);
        }
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-21
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 2013-10-27
      • 2019-12-26
      • 2016-12-15
      相关资源
      最近更新 更多