2014-04-08 39 views
1
var fs = require('fs'); 

var mongo = require("mongodb"); 

var config = JSON.parse(fs.readFileSync('./config.json')); 

var host = config.host; 

var port = mongo.Connection.DEFAULT_PORT; 

var db = new mongo.Db("Nodejs-introduction", new mongo.Server(host,port,{})); 

db.open(function(error){ 
console.log("we are connected " + host + " : " + port); 

db.collection("user",function(error,collection){ 
    console.log("we have the collection"); 

    collection.insert({ 
     name:"jarvis" 
    }, function(err,result){ 
     if(err) throw err; 

     console.log(result); 

     db.close(); 
    }); 

}); 

});數據庫連接在nodejs和mongodb之間不成功

對於上述程序。我得到以下錯誤在命令提示符下 enter image description here

錯誤後變化如下:

enter image description here

+0

其實上市之後db.collection''你從來沒有關閉回調這個問題。那麼它實際上在哪裏關閉?該類型錯誤表明您可能引用了超出範圍的內容。 –

+0

@NeilLunn正確安裝mongodb解決了這個問題。我認爲mongodb已經安裝,但事實證明它沒有。 –

回答

0

解決由R e在此安裝MongoDB的

0

您的連接是好的,我認爲問題可能出在這裏

collection.insert({ 
    name: "jarvis" 
}, function(err,result){ 
    console.log(err); 
}); 

您可能有問題嘗試登錄錯誤,而沒有與該插入錯誤。嘗試製作:

collection.insert({ 
    name: "jarvis" 
}, function(err,result){ 
    if(err) throw err; 

    console.log(result); 

    db.close(); 
}); 

並記住關閉db。

+0

錯誤未解決我將在進行更改後發佈以下錯誤。 –

+1

正確安裝mongodb解決了問題。我認爲mongodb已經安裝,但事實證明它沒有。 –