2013-03-21 114 views
2

我无法使用node.js和Mongodb包查询我的MongoDB数据库。无法使用node.js和Mongodb包查询MongoDB数据库

我已经成功地插入,像这样两个对象:

var mongo = require("mongodb"); 
var host = "127.0.0.1"; 
var port = mongo.Connection.DEFAULT_PORT; 
var db = new mongo.Db("nodejs-introduction", new mongo.Server(host, port, { }), {safe: true}); 
console.log(host); 
db.open(function(error) { 
    console.log("We are connected ", + host + ':' + port); 

    db.collection("user", { w:1 }, function(error, collection){ 
     console.log("We have the collection"); 

     collection.insert({ 
      id: "1", 
      name: "Foo Bar", 
      twitter: "Foo_Bar", 
      email: "[email protected]" 
     }, {w:1}, function() { 
      console.log("Succesfully inserted Foo Bar"); 
     }); 

     collection.insert({ 
      id: "2", 
      name: "Bar Foo", 
      twitter: "Bar_Foo", 
      email: "[email protected]" 
     }, {w:1}, function() { 
      console.log("Succesfully inserted Bar Foo"); 
     }); 
    }); 
}); 

一切顺利这里,没有错误。但是如果我想查询像这样的项目:

var mongo = require("mongodb"); 
var host = "127.0.0.1"; 
var port = mongo.Connection.DEFAULT_PORT; 
var db = new mongo.Db("nodejs-introduction", new mongo.Server(host, port, { }), {safe: false}); 
console.log(host); 
db.open(function(error) { 
    console.log("We are connected ", + host + ':' + port); 

    //collection is sort of table 
    db.collection("user", function(error, collection){ 
     console.log("We have the collection"); 
     collection.find({ "id": "1" }, function(error, cursor){ 
      cursor.toArray(function(error, users){ 
       if (users.length == 0) { 
        console.log("no user found"); 
       } else { 
        console.log("Found a user", users[0]); 
       } 
      }); 
     }); 

    }); 
}); 

然后我得到以下错误:

127.0.0.1 
We are connected NaN:27017 
We have the collection 

/path/to/query.js:14 
       if (users.length == 0) { 
         ^
TypeError: Cannot read property 'length' of null 

所以我不解的是,该变量的用户为空并且它不能找到任何比赛,但我不知道为什么。我做错了什么?

+0

可能文档中没有元素'users',因此返回'null'。你必须检查'null':if(users == null){...} else ... – 2013-03-21 10:55:44

+0

没有匹配,所以它返回null而不是空的Array。 – WiredPrairie 2013-03-21 11:02:49

+0

我明白,但我不明白的是为什么没有匹配。 – user1386906 2013-03-21 11:09:29

回答

1

找到了解决办法。 Mongodb没有运行。如果Mongodb没有运行,我可以如何插入MongoDB而没有任何错误?

+1

尝试检查您的'错误'回调参数;-) – heinob 2013-03-23 09:02:17