简体   繁体   中英

Select document by _id accessing database from MongoDB MLAB in Node.js

I am trying to access the document from MongoDB which was hosted on MLab but getting following error while access document with _id. Following is code for your reference

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

But getting below error when try to access the URL : http://localhost:3000/api/v1/todo/5870f7f1f36d2872530d26f1

TypeError: hex is not a function at Function.from (native) at Function.from (native) at new ObjectID (C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\bson\\lib\\bson\\objectid.js:52:32) at C:\\Kamlesh\\Angular2\\meantodos\\routes\\todos.js:23:14 at Layer.handle [as handle_request] (C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\express\\lib\\router\\layer.js:95:5) at next (C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\express\\lib\\router\\route.js:131:13) at Route.dispatch (C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\express\\lib\\router\\route.js:112:3) at Layer.handle [as handle_request] (C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\express\\lib\\router\\layer.js:95:5) at C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\express\\lib\\router\\index.js:277:22 at param (C:\\Kamlesh\\Angular2\\meantodos\\node_modules\\express\\lib\\router\\index.js:349:14)

I'm getting today a similar error related with some mongodb-core update.

I fixed it by forcing mongodb-core to the previous version i had:

npm install --save mongodb-core@1.3.18

Anyway, the first thing you have to check is that req.params.id has a valid hexadecimal 25 char string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM