如何重定向到创建的文档?

时间:2016-06-19 13:12:29

标签: javascript node.js express

如何将用户重定向到他刚使用express.js创建的doc / post的show动作?

以下是我用来创建doc的代码:

app.post('/doc/create', docController.postCreate );
app.get('/doc/:id', docController.getRecord );

exports.postCreate = ((req, res, next) => {

  const doc = new Doc({
    title: req.body.title
  });

  doc.save(req.body, (err /*, result*/) => {
    res.redirect('doc/{{{DOC_ID}}}'); // How can I get/pass the newly created ID
  });

});

1 个答案:

答案 0 :(得分:0)

数据库响应应返回已创建项目的ID。

// ucommment the result param
doc.save(req.body, (err, result) => {
  // ALWAYS handle errors!
  if (err) return res.status(500).send('Internal server error');
  // hopefully, the id is at the root of the result object, else, find out where it is and use it
  res.redirect('/doc/' + result.id);
});