我在我正在编写的nodejs应用程序中使用mongodb。
在我的代码中运行插入后,我收到以下错误:ReferenceError:在/home/safeuser/lunchand/routes/talktomongo.js:17:7中未定义集合
据我所知,只需在集合中运行insert即可创建它!如果我在终端中手动打开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 :(得分: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);
}
});
答案 1 :(得分:0)
我猜第17行应该是db.collection.insert(...
或_collection.insert(...