findOne with mongoskin and node

1k Views Asked by At

I'm trying (and failing miserably) to get a findOne function working on a mongodb. I followed this tutorial (http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/) and it works fine, but when I tried to get just a simple findOne going I have had such problems, can someone please help me out? I have searched every tutorial I can and I know you can't just use findone({_id: "idnumber"}), but I don't know what is wrong with mine:

router.get('/userlist/:id', function(req, res) {
db = req.db;
ObjectID = require('mongoskin').ObjectID;
var userToGet = req.params.id;
db.collection('userlist').findOne({_id: db.ObjectID.createFromHexString(userToGet)}, function(err, result) {
    console.log(result.username);
});
});

I get the error "Cannot call method 'createFromHexString' of undefined", where should I require my mongoskin.objectid?

My findall works perfectly:

router.get('/userlist', function(req, res) {
db = req.db;
db.collection('userlist').find().toArray(function (err, items) {
    res.json(items);
});
});

Any help would be GREATLY appreciated.

1

There are 1 best solutions below

2
On BEST ANSWER

Your problem is, when you do:

db.ObjectID.createFromHexString(userToGet)

, you should be doing:

ObjectID.createFromHexString(userToGet)

because you already declared the ObjectID variable when you did:

ObjectID = require('mongoskin').ObjectID;

Tip: never declare a variable without the var statement (unless it's REALLY necessary), because if you do that, it'll be in the global scope. Do this instead:

var ObjectID = require('mongoskin').ObjectID;