正在导出mongodb'db'到另一个node.js模块
Exporting mongodb 'db' to another node.js module
我尝试使用mongodb MongoClient
连接到数据库一次,然后在整个应用程序的其他地方使用db
变量。我遵循文件中提供的模式。但由于某种原因,我的db
变量即将出现undefined
。这是我的代码:
在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: Cannot read property 'collection' of undefined
:
var questionsCursor = mongo.dbconnection.collection('Question').find({"Vertical": "Cellular"} );
我错过了什么?
dbconnection
在回调函数中定义时无法导出。如果您想重用mongodb connneciton instance
,您可以从本机mongodb驱动程序导出一个函数use promise(更多信息,请查看官方节点mongodb驱动器):
db.js
`use strict';
var MongoClient = require("mongodb").MongoClient;
function getDb() {
return MongoClient.connect(yourConnString).then(function (db) {
return db;
})
}
module.exports = getDb();
example.js
'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;
})
});
相关文章:
- 使用JS函数来使用另一个函数的语法?node.js
- 如何使用javascript express node将变量从控制器中的一个方法公开.js到另一个控制器.js
- 如何重定向到node.js中的另一个页面
- 在Node.js中,从同一文件中的另一个函数引用一个函数会导致'ReferenceError:-函数-未定义
- 在 node.js 中,模块中的一个文件如何查看模块中另一个文件中的函数
- 使用 Node js 从另一个文件调用两个文件
- 使用 node.js 启动另一个节点应用程序
- 在 Node.js 中从一个绝对路径减去另一个绝对路径
- 如何从一个文件中导出字符串,并在NODE.js中的另一个文件上要求()导出的字符串
- 如何动态生成将对象转移到另一个Node进程的代码
- 在node.js中用一个模块替换另一个模块
- Node.js聊天服务器,当另一个用户发送数据时,客户端断开连接
- 在独立脚本上运行的函数在另一个脚本Javascript node.js上不起作用
- Node.js-每个Express请求的域,位于另一个域内
- 使用jQuery和Node.JS中的表单中的数据重定向到另一个网页
- 管道化node.js脚本's stdout到另一个's stdin没有'不起作用
- 如何发送HTTP请求提交表单在node.js到另一个网站
- javascript可以使用node.js从另一个js文件中获取函数吗?
- 正在导出mongodb'db'到另一个node.js模块
- 我如何从另一个Node.js脚本中运行Node.js脚本