我做了一个测试页面:两个静态图片,一段取自mongodb的文字。然后不停的刷新网页。出现奇怪的现象: 我用如下代码连接数据库:
var mongodb=require('mongodb')
, mongoserver=new mongodb.Server('localhost',27017)
,dbtest=new mongodb.Db('test',mongoserver,{w:-1});
如果我将这些语句写在路由的响应函数里就没问题。但是如果我将以上代码写在一个js文件中,封装成模块,然后引用,即一下这样:
模块文件:
var mongodb=require('mongodb')
, mongoserver=new mongodb.Server('localhost',27017)
,dbtest=new mongodb.Db('test',mongoserver,{w:-1});
module.exports=dbtest;
路由响应函数中调用:
var dbtest=require('dbcon');
(其他代码都相同)就会出现 Error: db object already connecting, open cannot be called multiple times 错误。
请问这是怎么回事呢,封装到模块和写在响应函数里不一样吗?代码都是一样的啊?
用MongoClient, 采用异步将数据库赋给宿主的方式连接数据库
'use strict’;
var MongoClient = require(‘mongodb’).MongoClient;
function db(app) {
console.log(‘db required’);
MongoClient.connect("mongodb://localhost:27017/mydb", function (err, database) {
if (err) {
console.log(err);
} else {
app.db = database; // 将数据库对象赋值给宿主对象
if (app.onDatabaseReady) {
app.onDatabaseReady(database); //触发宿主对象中需要在数据库连接成功后运行的代码
}
console.log(“Connected to Database”);
}
});
}
module.exports = db;
主程序:
var db = require(‘…/path/to/db’);
db(app);
…
app.db.xxxx
Error: db object already connecting, open cannot be called multiple times
at Db.open (X:\BYSJ\Project\simulat\node_modules\mongodb\lib\mongodb\db.js:224:11)
at exports.index (X:\BYSJ\Project\simulat\routes\index.js:16:12)
at callbacks (X:\BYSJ\Project\simulat\node_modules\express\lib\router\index.js:161:37)
at param (X:\BYSJ\Project\simulat\node_modules\express\lib\router\index.js:135:11)
at pass (X:\BYSJ\Project\simulat\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (X:\BYSJ\Project\simulat\node_modules\express\lib\router\index.js:170:5)
at Object.router (X:\BYSJ\Project\simulat\node_modules\express\lib\router\index.js:33:10)
at next (X:\BYSJ\Project\simulat\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.methodOverride [as handle] (X:\BYSJ\Project\simulat\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:37:5)
at next (X:\BYSJ\Project\simulat\node_modules\express\node_modules\connect\lib\proto.js:190:15)