skip to Main Content

Consider:

app.get("/posts/:postId", function(req, res) {

  const requestedPostId = req.params.postId;

  Post.findOne({_id: requestedPostId}, function(err, post) {
    res.render("post", {
      title: post.title,
      content: post.content
    });
  });

});

This is what used to work for me, using Express.js and Mongoose. How can I fix it?

3

Answers


  1. Chosen as BEST ANSWER

    I got the solution thanks to my friend @Sean. Instead of the callback function, I have to replace it with a .then() function:

    app.get("/posts/:postId", function(req, res) {
    
      const requestedPostId = req.params.postId;
    
      Post.findOne({_id: requestedPostId}).then(post => {
    
        res.render("post", {
    
          title: post.title,
    
          content: post.content
        });
      });
    });
    

  2. MongoDB has removed callbacks from its Node.js driver as of version 5.0. See findOne.

    If you really need to use callbacks instead of promises, you will need to use an older version of the driver.

    Login or Signup to reply.
  3. In version 5.0, MongoDB has removed callbacks from its node.js driver. So now you can leverage the Promise instead of callback.

    Updated Code:

    Post.findOne({_id: requestedPostId}).then(post =>{
        res.render("post", {
          title: post.title,
          content: post.content
          });
        });
    

    Also Refer: https://mongodb.github.io/node-mongodb-native/5.0/classes/Collection.html#findOne

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search