【问题标题】:Select document by _id accessing database from MongoDB MLAB in Node.js通过_id从Node.js中的MongoDB MLAB访问数据库选择文档
【发布时间】:2017-05-22 15:34:56
【问题描述】:

我正在尝试从托管在 MLab 上的 MongoDB 访问文档,但在使用 _id 访问文档时出现以下错误。以下是供您参考的代码

var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://<<UserName>>:<<Password>>@aadds157248.mlab.com:57248/<<DatabaseName>>',['temp1']);
router.get('/todo/:id',function(req,res,next){
var ObjectID = mongojs.ObjectID;
var o_id = new ObjectID (req.params.id);
db.temp1.findOne({
   '_id': o_id
},
function(err,temp1){
    if (err){
        res.send(err);
    }
    else {
        res.json(temp1);
    }
})
});

但尝试访问 URL 时出现以下错误:http://localhost:3000/api/v1/todo/5870f7f1f36d2872530d26f1

TypeError: hex 不是函数 在 Function.from (本机) 在 Function.from (本机) 在新的 ObjectID (C:\Kamlesh\Angular2\meantodos\node_modules\bson\lib\bson\objectid.js:52:32) 在 C:\Kamlesh\Angular2\meantodos\routes\todos.js:23:14 在 Layer.handle [as handle_request] (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\layer.js:95:5) 在下一个(C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\route.js:131:13) 在 Route.dispatch (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\route.js:112:3) 在 Layer.handle [as handle_request] (C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\layer.js:95:5) 在 C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\index.js:277:22 在参数处(C:\Kamlesh\Angular2\meantodos\node_modules\express\lib\router\index.js:349:14)

【问题讨论】:

  • 你能打印 req.params.id 看看你在服务器端得到了什么价值吗?做 console.log(req.params.id);
  • @Sumeet 是的,我尝试获取我从问题中提到的 URL 发送的值。

标签: node.js mongodb


【解决方案1】:

我今天遇到了与某些 mongodb-core 更新相关的类似错误。

我通过强制 mongodb-core 到我以前的版本来修复它:

npm install --save mongodb-core@1.3.18

无论如何,您首先要检查的是 req.params.id 有一个有效的十六进制 25 字符字符串。

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多