admin管理员组

文章数量:1380991

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?

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?

Share Improve this question edited Mar 7, 2023 at 11:46 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Mar 2, 2023 at 13:25 Aniruddha BiswasAniruddha Biswas 211 gold badge1 silver badge3 bronze badges 1
  • 2 Seems like they dropped support for callbacks. They throw an error on purpose, can be seen here. You have to use async/await as shown in their example. – Palladium02 Commented Mar 2, 2023 at 13:41
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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

本文标签: javascriptMongooseError ModelfindOne() no longer accepts a callbackStack Overflow