如何通过节点js express中的API POST路由保存两条记录

How to save two records via API POST route in node js express

我有这个 api 路由功能,需要更新主题记录以包含 post 的引用,然后保存正在创建的实际 post 记录。有没有更好的方法来做我想做的事?可能吗?

const express = require('express');
const router = express.Router();

router.post('/:id/posts',  (req,res) => {
  const newPost = new Post({
      post: req.body.post,
      description: req.body.description,
      topic_id: req.params.id
  });
   Topic.findById(req.params.id)
      .then(topic => {
          topic.posts.push(newPost._id);
      })
          .catch(err => {
              res.send(err);
          });
  //how do i save this topic record I find and push an id into.


  newPost.save().then(post => res.json(post));
});

github 第 33 行:https://github.com/wolffles/bloccit-node/blob/express/routes/api/topics.js

问题

如何保存找到并修改的主题记录?

回答

使用最新的 JS async await 语法试试这个。

router.post('/:id/posts',  async (req,res) => {
  const newPost = new Post({
      post: req.body.post,
      description: req.body.description,
      topic_id: req.params.id
  });
  try {
     await Topic.findById(req.params.id, (err, doc) => {
       doc.posts.push(newPost._id);
       doc.save();
     });
     const post = await newPost.save()
     res.json(post)
  } catch(err) {
     res.send(err)
  }
});

让我知道这是否适合你。

只需将文档保存在主题 return 的承诺成功中即可。就像我在下面写的一样。 让我知道这是否有效。

const express = require('express');
const router = express.Router();

router.post('/:id/posts',  (req,res) => {
  const newPost = new Post({
      post: req.body.post,
      description: req.body.description,
      topic_id: req.params.id
  });
   Topic.findById(req.params.id)
      .then(topic => {
          topic.posts.push(newPost._id);
          //now update the newPost
          newPost.topicObj = topic;
           newPost.save().then(post => res.json(post));
      })
          .catch(err => {
              res.send(err);
          });
  //how do i save this topic record I find and push an id into.


 
});