简体   繁体   中英

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

Using express.js framework for MERN stack app. It's my first js full stack app, so new to a lot of these functions. Need to POST a new post to a topic and also update topic. Posts with a reference to the Posts collection.

Here's 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

line 31 is the code snippet.

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.

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)

It's look like your using TypeScript or Ecmascript so you could do : (look at async and await keyword)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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