2016-03-03 56 views
1

我是相當新的NodeJSMongoDB查找在MongoDB的ID返回null

我試圖做一個很基本的東西,但它似乎並不奏效。
我相信我在某處丟失了某些東西。

基本上,我試圖從基於id的數據庫中找到一個用戶。
這裏是我的代碼:

function findUser(id, cb) { 
    MongoClient.connect(cs, function(err, db) { 
     var col = db.collection('users'); 
     col.findOne({ _id: id }, function(err, user) { 
      // Value of user here is always null 
      // However, if I manually check the database, 
      // I can clearly see that the user with the 
      // same id does exists. 
      return cb(err, user); 
     }); 
    }); 
} 

回答

1

我假設你id類型爲string

如果是這樣的話,你需要將其轉換爲一個適當的蒙戈ObjectID

試試這個代碼:

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

function findUser(id, cb) { 
    MongoClient.connect(cs, function(err, db) { 
     var col = db.collection('users'); 
     col.findOne({ _id: new ObjectID(id) }, function(err, user) { 
      return cb(err, user); 
     }); 
    }); 
} 
+0

非常感謝月亮!我會試一試。 – nirali35

+0

這似乎是工作。再次感謝。 – nirali35

0

我使用這個代碼:

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

app.get('/api/users/:id', function (req, res) { 
    db.collection('users', function (err, collection) { 
     collection.findOne({ 
      _id: new ObjectID(req.params.id) 
     }, function (err, result) { 
      res.send(result); 
     }); 
    }); 
}); 

它的工作原理!