[英]“Collection is not defined” error on insert with mongodb
我在當前正在編寫的nodejs應用程序中使用mongodb。
在我的代碼中運行插入后,我得到以下錯誤:ReferenceError:未在/home/safeuser/lunchand/routes/talktomongo.js:17:7定義集合
據我所知,僅在集合中運行insert即可創建它! 如果我在終端上手動打開mongo並運行show 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);
}
});
嘗試將集合名稱添加到對象中,如下所示:
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);
}
});
我猜想第17行實際上應該是db.collection.insert(...
或_collection.insert(...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.