2

我正在尝试(并且惨遭失败)让 findOne 函数在 mongodb 上工作。我遵循了本教程(http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/),它工作正常,但是当我试图获得一个简单的 findOne 时,我有有这样的问题,有人可以帮我吗?我已经搜索了所有我能找到的教程,我知道你不能只使用 findone({_id: "idnumber"}),但我不知道我的有什么问题:

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

我收到错误“无法调用未定义的方法'createFromHexString'”,我应该在哪里需要我的 mongoskin.objectid?

我的 findall 完美运行:

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

任何帮助将不胜感激。

4

1 回答 1

2

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;
于 2014-12-17T02:06:45.613 回答