2013-08-20 77 views
4

因此,我正在关注tutsplus.com上的一个Node.js教程课程,它迄今为止一直很棒。节点JS:没有插入到mongodb

我在关于MongoDB的教训上,我已经有点失落了。我不知道为什么这对我不起作用,因为它在视频中工作,我的代码是相同的。我能想到的是,自从一年前制定课程以来,已经有了一个更新。

从不同的角度尝试到console.log我认为数据在开始时没有正确插入,因此没有返回。

除了cursor.toArray()的回调之外,一切似乎都在按预期发射。

我目前正在学习node和mongodb,所以如果我犯了一个明显的错误,请耐心等待。

我被指示写入以下文件,然后在命令行中执行它。

编辑:

我已经缩小的问题降到插入脚本。当通过CLI插入数据时,它会将其恢复。

var mongo = require('mongodb'), 
    host = "127.0.0.1", 
    port = mongo.Connection.DEFAULT_PORT, 
    db = new mongo.Db('nodejsintro', new mongo.Server(host, port, {})); 

db.open(function(err){ 
    console.log("We are connected! " + host + " : " + port); 

    db.collection("user", function(error, collection){ 

     console.log(error); 

     collection.insert({ 
      id: "1", 
      name: "Chris Till" 
     }, function(){ 
       console.log("Successfully inserted Chris Till") 
     }); 

    }); 

}); 
+1

所以有一个Mongo shell带有mongo,名为'mongo'。当你查询那里的相同数据时会发生什么? – Paul

+0

如果我在终端输入'mongo',我得到一个错误,说不能连接。 –

+0

那么,在代码中,你可以添加'if(err)return console.log(err);'来检查同样的东西。虽然通常它会抛出错误,因为如果出现错误,其他数据将不会被定义。 – Paul

回答

2

你确定你真的连接到mongo吗? 当你从cli连接到mongo并键入'show dbs'时,你会看到nodejsintro? 集合是否存在?

此外,从你的代码

db.open(function(err){ 
    //you didn't check the error 
    console.log("We are connected! " + host + " : " + port); 

    db.collection("user", function(error, collection){ 
     //here you log the error and then try to insert anyway 
     console.log(error); 

     collection.insert({ 
      id: "1", 
      name: "Chris Till" 
     }, function(){ 
       //you probably should check for an error here too 
       console.log("Successfully inserted Chris Till") 
     }); 

    }); 

}); 

如果您已经调整了记录,并确保你没有得到任何错误,让我们尝试改变一些连接信息的。

var mongo = require('mongodb'); 

var Server = mongo.Server, 
    Db = mongo.Db, 
    BSON = mongo.BSONPure; 

var server = new Server('localhost', 27017, {auto_reconnect: true}); 
db = new Db('nodejsintro', server); 

db.open(function(err, db) { 
    if (!err) { 
     console.log("Connected to 'nodejsintro' database"); 
     db.collection('user', {strict: true}, function(err, collection) { 
      if (err) { 
       console.log("The 'user' collection doesn't exist. Creating it with sample data..."); 
       //at this point you should call your method for inserting documents. 
      } 
     }); 
    } 
}); 
+0

我已经试过控制台日志记录所有的错误,他们都返回null。当我运行'show dbs'我可以看到'nodejsintro \t 0.203125GB' –