Node.js Question

NodeJS/MongoDB POST request times out

I'm kind of a noob here but I've encountered a strange bug, I've been trying to test out my GET/POST requests to my mongoDB via Postman, GET works perfectly but POST doesn't seem to do anything, it just keeps loading forever and times out eventually, but the analytics from modulus.io (where I hosted my db) says they received a query immediately after I press POST. Here's the relevant code:

My post controller:

`module.exports.postsCreateOne = function(req, res) {
if(req.params && req.params.userid) {
User.findById(req.params.userid)
.exec(function(err, user) {
if(!user) {
sendJsonResponse(res, 404, {"message":"user not found"});
return;
}
else if (err) {
sendJsonResponse(res, 404, err);
return;
}
else {
addPost(req, res, user);
}
})}`

var addPost = function(req, res, user) {
user.posts.unshift({
text: req.body.text
});}


Routes:

router.post('/posts/:userid', ctrlPosts.postsCreateOne);


Also, for better understanding, I've recorded a short video of it

Answer

If there is no response it means you forgot to send something back.

In your code if it is all successful it will not return anything.

Futher at the param check you dont return something if it is not valid, it looks like you have no error case and if the userid is invalid it also fails

Maybe try somthing like this:

const ObjectId = mongoose.Types.ObjectId
exports.postsCreateOne = function(req, res, next) {
  if (!ObjectId.isValid(req.params.userid)) {
    return res.status(400).json({
      error: 'invalid userid'
    })
  }
  User.findById(req.params.userid)
    .exec(function(err, user) {
        if (err)
          return next(err)
        if (!user) {
          return res.status(404).json({
            message: 'user not found'
          })
        }
        user.posts.unshift({
          text: req.body.text
        })
        // save something
        res.json({
          status: 'ok'
        })
      }
    }
}

And you should consider Promises because they make your live easier. And if you use next(err) for all your errors you should log them in your error handler.