繁体   English   中英

如何在NodeJ中通过POST API推送引用并保存?

[英]How to push reference and save via POST API in NodeJs?

使用针对MERN堆栈应用程序的express.js框架。 这是我的第一个js全栈应用程序,因此其中许多功能都是新功能。 需要POST一个新的职位,以一个主题,并同时更新的话题。 引用Posts集合的帖子。

这是server.js

router.post('/:id/posts', (req,res) => {
  const { id } = req.params // works

  const newPost = new Post({
    post: req.body.post,
    description: req.body.description,
    topic_id: id
  })

  const topic = Topic.findById(id).then(topics => res.json(topics))

  console.log(topic.posts)
  // and I don't understand why my topic object is always undefined I need to push a reference into it I think.

  //need to save/update topic object to db
  //need to save new post
  //my other post function has newPost.save().then(post => res.json(post) and it works. but in this function it doesn't. 
});

这是架构

const TopicSchema = new Schema({
    topic: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    posts: [
        { 
            type: Schema.Types.ObjectId,
            ref: 'post'
        }
    ],
    date: {
        type: Date,
        default: Date.now
    }
});   

如果有人可以引导我完成我做错的事情,我将不胜感激。 如果需要更多信息,还将推送到GitHub

第31行是代码段。

要保存,请执行以下操作:

const topic = Topic.findById(id).then(topic => {
    topic.posts.push(newPost);
    topic.save(err => {
       if (err) {
         res.sendStatus(400)
       } else {
         res.sendStatus(200)
       }
    })
})

如果要将更新后的主题发送回客户端,可以在保存回调中按主题ID查询。

这行是错的

const topic = Topic.findById(id).then(topics => res.json(topics))

在这里,您正在进行异步调用,因此topic是一个promise,而topic.posts是未定义的(正常)

就像您使用TypeScript或Ecmascript一样,您可以执行以下操作:(查看asyncawait关键字)

router.post('/:id/posts', async (req,res) => {

  const { id } = req.params // works

   const newPost = new Post({
     post: req.body.post,
     description: req.body.description,
     topic_id: req.body.id
   })

   try {
     const topic = await Topic.findById(id);
   }catch(err){
      // send a status 404 cause the id dont match any topic
      return;
   }
   console.log(topic.posts) //undefined but i still need to add post._id to my topic.posts 

     //attempt to save newPost object
   try {
     const post = await newPost.save();
     res.json(post);
   }catch(err){
      // You can send a internal error status cause something went wrong
   }
     // returns not post json but a topic json?
     // plus error
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM