2013-08-20 73 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' –