2015-01-13 43 views
0

我是NodeJS的新手,我正在使用MongoDB实现。然而,我有一个错误,在我的眼睛很奇怪:TypeError: Cannot call method 'find' of undefined.我试图从节点mongo模块使用'find'方法,collection.find({id: "1"}, callback),但我得到的只是错误。然而,奇怪的是,一个插入工作。问题是什么?Typerror:mongo模块的查找方法是undefined

db.collection('users', function(error, collection) 
{ 
    console.log('Collection:'); 
    // ================ THIS WORKS ================= 
    // insert : 

    // collection.insert({ 

    // id: "1", 
    // name: "Marciano", 
    // email: "[email protected]", 

    // }, function() 
    // { 
    // console.log('inserted!'); 
    // }); 

    // collection.insert({ 

    // id: "2", 
    // name: "Edward Elric", 
    // email: "[email protected]", 

    // }, function() 
    // { 
    // console.log('inserted!') 
    // }); 
    // ======= THIS DOESNT WORK ======== 
    // select: 
    // specify an object with a key for a 'where' clause 
    collection.find({'id': '1'}, function(error, cursor) 
    { 
      //cursor : iterateing over results 

      cursor(function(error, user) 
      { 
       console.log("found:" + user); 
      }) 

    }) 



}); 
+1

怎么样collection.findOne({'id':'1'})?你是否还确认回调中没有任何错误,包括插入? –

+1

该错误指示'collection'是'undefined'。我发现很难相信'insert'在相同的条件下工作。 –

回答

0

那不是你如何遍历一个Cursor对象从.find()返回。改为使用.each().toArray()方法来处理结果。

collection.find({ "id": 1 }).toArray(function(err,data) { 
    // data is an array of objects from the collection 
}); 
0

这是造成beucase你插入记录到数据库和不等待回调。如果你想这样做,我建议你使用async和方法瀑布。 但无论如何,它会更好地使用Mongoose,而不是你现在正在使用。 并写这样的东西

var mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost/collection'); 

var user = new User({ name: 'John' }); 
user.save(getInsertedUsers); 

var getInsertedUsers = function(){ 
    User.find({ name: "John" }, echoUsers); //if you want to get just users named john or 
    User.find({}, echoUsers); 
} 
var echoUsers = function(users) 
{ 
    console.log(users); 
}