我正在通过 Ciaran Jessup 的创建基本博客的演练作为对节点的介绍。当我尝试查看一篇文章时,我收到以下错误:
500 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at Function.createFromHexString (/Users/me/Dropbox/projects/node/howtonode_blog/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:212:11)
at /Users/me/Dropbox/projects/node/howtonode_blog/articleprovider-mongodb.js:38:64
at /Users/me/Dropbox/projects/node/howtonode_blog/articleprovider-mongodb.js:16:10
at Db.collection (/Users/me/Dropbox/projects/node/howtonode_blog/node_modules/mongodb/lib/mongodb/db.js:484:44)
at ArticleProvider.getCollection (/Users/me/Dropbox/projects/node/howtonode_blog/articleprovider-mongodb.js:14:11)
at ArticleProvider.findById (/Users/me/Dropbox/projects/node/howtonode_blog/articleprovider-mongodb.js:34:10)
at app.post.articleProvider.addCommentToArticle.person (/Users/me/Dropbox/projects/node/howtonode_blog/app.js:51:19)
at callbacks (/Users/me/Dropbox/projects/node/howtonode_blog/node_modules/express/lib/router/index.js:161:37)
at param (/Users/matty/Dropbox/projects/node/howtonode_blog/node_modules/express/lib/router/index.js:135:11)
at param (/Users/matty/Dropbox/projects/node/howtonode_blog/node_modules/express/lib/router/index.js:132:11)
以下是相关的代码:
来自 app.js:
app.get('/blog/:id', function(req, res) {
articleProvider.findById(req.param.id, function(error, article) {
res.render('blog_show.jade',{title: article.title, article: article})
})
})
来自 articleprovider-mongodb.js:
ArticleProvider.prototype.findById = function(id, callback) {
this.getCollection(function(error, article_collection) {
if(error) callback(error);
else {
article_collection.findOne(
// THIS IS THE LINE IN QUESTION BELOW
{_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(id)},
function(error, result) {
if(error) callback(error);
else callback(null, result);
}
);
}
});
};
我试图将id
对象转换为字符串,并尝试直接将其作为对象传递。但是,我的 javascript 非常糟糕,而且我没有运气。我尝试过传递String(id)
,id + ""
而不是id
与:
{_id: id}
和
{_id: article_collection.db.bson_serializer.ObjectID(id)}
我真的很感激有人指出我做错了什么。
谢谢阅读!
编辑: console.log("req.param.id is " + req.param.id)
输出“req.param.id is undefined” 但是,urlhttp://localhost:3000/blog/516afb1064036bb345000001
是正确的,因为我将 516afb1064036bb345000001 直接传递给ArticleProvider.findById
调用并且它有效。
编辑 2:当我更改req.param.id
为req.params.id
. 但是,在我的app.post
函数中,我使用了param
如下的单数并且仍然有效:
articleProvider.save({
title: req.param('title'),
body: req.param('body')
} ...
为什么单数param
在这里起作用?是否params
特指在 URI 中传递的参数?