Javascript 出口mongodb';db';到另一个node.js模块
我正在尝试使用Javascript 出口mongodb';db';到另一个node.js模块,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我正在尝试使用mongodb MongoClient连接数据库一次,然后在整个应用程序的其他位置使用db变量。我正在遵循中提供的模式。但是由于某种原因,我的db变量出现了未定义的。这是我的密码: 在mongo.js中: var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server; var dbconnection; Mo
mongodb MongoClient
连接数据库一次,然后在整个应用程序的其他位置使用db
变量。我正在遵循中提供的模式。但是由于某种原因,我的db
变量出现了未定义的。这是我的密码:
在mongo.js中
:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var dbconnection;
MongoClient.connect("mongodb://127.0.0.1/smartmonthly", function (err, db) {
if (err) {
console.log("connection err ", err);
throw err;
} else {
console.log("successfully connected to the database");
this.dbconnection = db;
}
});
module.exports.dbconnection = dbconnection;
在Question.js
中:
var mongo = require('./mongo.js');
module.exports = {
all: function() {
var questionsCursor = mongo.dbconnection.collection('Question').find({"Vertical": "Cellular"} );
questionsCursor.toArray(function(err, documents) {
console.log("documents length ", documents.length);
questions = documents;
mongo.db.close();
return questions;
});
}
}
此代码引发错误:TypeError:无法读取此行中未定义的属性“collection”:
var questionsCursor = mongo.dbconnection.collection('Question').find({"Vertical": "Cellular"} );
我错过了什么 在回调函数中定义时,无法导出数据库连接。如果要重用mongodb connneciton实例
,可以从本机mongodb驱动程序导出函数use promise(更多信息视图):
db.js
example.js
您应该执行dbconnection=db;而不是this.dbconnection=db;我试过了,但它产生了相同的错误。因为module.exports.dbconnection=dbconnection;是在回调之前执行的,这就是为什么导出的dbconnection是未定义的解决方案:module.exports.getConnection=function(){return dbconnection;},然后在Question.js中可以执行mongo.getConnection().collection…谢谢@oliv37,这可以工作,但现在Question.js中的“all”函数在数据库操作完成之前返回,所以我得到一个空数组,它被发送回http。如何让它等待并实际返回从数据库返回的问题对象?
`use strict';
var MongoClient = require("mongodb").MongoClient;
function getDb() {
return MongoClient.connect(yourConnString).then(function (db) {
return db;
})
}
module.exports = getDb();
'use strict';
var getDbIns = require('./db');
getDbIns.then(function (db) {
var col = db.collection("tmp");
return col.insertOne({name: 'test'}).then(function (res) {
console.log(res.insertedCount);
db.close();
return res.insertedCount;
})
});