2014-04-24 51 views
0

我正在使用我正在寫的nodejs應用程序中的mongodb。「集合未定義」與插入與mongodb的錯誤

當我運行的代碼插入,我收到以下錯誤回:的ReferenceError:集合不/home/safeuser/lunchand/routes/talktomongo.js:17:7

就定義爲I從文檔中可以看出,只需在集合中運行插件就可以創建它!如果我在終端上手動打開mongo並運行show dbs,我也永遠不會在dbs列表中看到lunchand,只是本地和管理員。

這是我正在使用的代碼。第17行是collection.insert所在的位置。任何幫助將不勝感激。

//Declarations 
var mongo = require('mongodb'), 
    Server = mongo.Server, 
    Db = mongo.Db, 
    server = new Server('localhost', 27017, {auto_reconnect: true}), 
    db = new Db('lunchand', server); 

//Open database 
db.open(function(_err, _db) { 
    if(!_err) { 
     console.log("Connected to lunchand DB"); 
     db.collection('lunchers', {strict: true}, function(_err, _collection) { 
      if(_err) { 
       console.log("Lunchers collection doesn't exist! Let's fix that!"); 
       var testLuncher = {username:"username",pwd:"password",officeLocation:"Office Location",teams:"teams",shark: true}; 
       db.collection('lunchers', function(_err, _collection) { 
        collection.insert(testLuncher, {safe:true}, function(_err, _result) {}); 
       }); 
      } else { 
       console.log("Oh it exists"); 
      } 
     }); 
    } else { 
     console.log("Error Connecting to Station DB: " + _err); 
    } 
}); 

回答

0

嘗試添加名稱的集合對象是這樣的:

db.collection("lunchers").insert(testLuncher,function(err, element){ 
        console.log("element inserted"); 
        }); 

可能是你的代碼應該是這樣的:

var mongo = require('mongodb'), 
    Server = mongo.Server, 
    Db = mongo.Db, 
    server = new Server('localhost', 27017, {auto_reconnect: true}), 
    db = new Db('lunchand', server); 

//Open database 
db.open(function(_err, _db) { 
    if(!_err) { 
     db.collection('lunchers', {strict: true}, function(_err, _collection) { 
      if(_err) { 
       var testLuncher = {username:"username",pwd:"password",officeLocation:"Office Location",teams:"teams",shark: true}; 
       db.collection("lunchers").insert(testLuncher,function(err, element){ 
       console.log("element inserted"); 
       }); 


      } else { 
       console.log("Oh it exists"); 
      } 
     }); 
    } else { 
     console.log("Error Connecting to Station DB: " + _err); 
    } 
}); 
+0

非常感謝你,我變得如此無奈d。這工作完美! – theTHP

+0

我很高興幫助你 –

0

我猜想,行17應實際上是db.collection.insert(..._collection.insert(...