简体   繁体   English

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

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

Using express.js framework for MERN stack app. 使用针对MERN堆栈应用程序的express.js框架。 It's my first js full stack app, so new to a lot of these functions. 这是我的第一个js全栈应用程序,因此其中许多功能都是新功能。 Need to POST a new post to a topic and also update topic. 需要POST一个新的职位,以一个主题,并同时更新的话题。 Posts with a reference to the Posts collection. 引用Posts集合的帖子。

Here's server.js : 这是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. 
});

this is the schema 这是架构

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
    }
});   

If anyone could walk me through what I'm doing wrong I'd be grateful. 如果有人可以引导我完成我做错的事情,我将不胜感激。 Also pushed to GitHub if more info is needed 如果需要更多信息,还将推送到GitHub

line 31 is the code snippet. 第31行是代码段。

To save do this: 要保存,请执行以下操作:

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

You can query by topic ID in the save callback if you want to send the updated topic back to client. 如果要将更新后的主题发送回客户端,可以在保存回调中按主题ID查询。

This line is wrong 这行是错的

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

Here you are doing asynchronoous call so topic will be a promise and topic.posts will be undefined (normal) 在这里,您正在进行异步调用,因此topic是一个promise,而topic.posts是未定义的(正常)

It's look like your using TypeScript or Ecmascript so you could do : (look at async and await keyword) 就像您使用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