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
3 Answers
Reset to default 2MongoDB 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
版权声明:本文标题:javascript - MongooseError: Model.findOne() no longer accepts a callback - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744502817a2609418.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论