文档

时间:2019-06-14 21:25:15

标签: node.js mongoose hook

之前曾问过几个类似的问题,但我无法获得适用于此用例的任何解决方案。

我正在尝试编写一个预提交钩子,该钩子每次保存新的“记录”文档时都会生成一个自动递增的ID号。

正在创建自动增量ID。我可以通过检查console.log来验证这一点。

问题是未在保存的文档上设置RecordID。保存该文档时,在save()调用中设置了正确的值,但未在pre save钩子中设置了RecordID。

记录模型

async function getNextSequence(name) {

  let seq, result;

  try {
    result = await counters.findOneAndUpdate({
      _id: name
    }, {
      // Increment sequence by 1
      $inc: { seq: 1 }
    });
  }
  catch (error) {
    console.error(`getNextSequence failed ${error}`);
  }

  return result.seq;

}

// Pre save hook
RecordsSchema.pre('save', (next) => {
  // Get document being saved
  let record = this;

  // Get next RecordID auto increment number
  getNextSequence('RecordID').then(nextID => {
    // Set RecordID
    if (nextID) {
      record.RecordID = nextID;
    }
    // nextID is showing up correctly
    // record object also shows up correctly in the log,
    // but it does NOT show up in the database
    console.log(`RecordsSchema.pre ${nextID} ${JSON.stringify(record)}`);
    next();
  }).catch((error) => {
    console.error(`getNextSequence failed ${error}`);
  });

});

记录save()通话

router.post('/', (req, res, next) => {

  let record = new records();
    record.Title = req.body.Title;
    record.Location = req.body.Location;

  record.save().then(record => {
    res.status(200).json(record);
  }).catch((error) => {
    console.log(`${origin} ${error}`);
    res.status(500).send('Server error');
  });

});

结果

记录标题和位置已正确保存。但是,没有保存RecordID。我还尝试了使用post save钩子,并且发生了相同的问题。

RecordsSchema.post('save', (doc) => {
  // Get document being saved
  let record = doc;

  // Get next RecordID auto increment number
  getNextSequence('RecordID').then(nextID => {
    // Set RecordID
    if (nextID) {
      record.set( { RecordID: nextID } );
    }
    console.log(`RecordsSchema.post ${nextID} ${JSON.stringify(record)}`);
    //next();
  }).catch((error) => {
    console.error(`getNextSequence failed ${error}`);
  });

});

1 个答案:

答案 0 :(得分:0)

我将arrow函数更改为函数表达式以解决此问题。 arrow function未绑定到this关键字。在这种情况下,需要函数表达式,因为Mongoose保存钩子返回绑定到this关键字的要保存的文档。

// Pre save hook
RecordsSchema.pre('save', function(next) {
  // Get document being saved
  let record = this;

  // Get next RecordID auto increment number
  getNextSequence('RecordID').then(nextID => {
    // Set RecordID
    if (nextID) {
      record.RecordID = nextID;
    }
    next();
  }).catch((error) => {
    console.error(`getNextSequence failed ${error}`);
  });

});