这是我连接mongodb的base_mongodb.js
var MongoClient = require('mongodb').MongoClient
, ObjectId = require('mongodb').ObjectID
, assert = require('assert')
, Util = require('./util')
, db;
module.exports = function(){
var self = this;
this.findOneById = function(tableName,id,callback){
connection(function (db) {
db.collection(tableName,function(err,collection){
var mongoId = ObjectId(id);
var cursor = collection.find({'_id':mongoId});
cursor.toArray(function(err,docs){
if(err){
callback(false);
}else{
callback(docs);
}
cursor.rewind();
});
});
})
};
/**
* 连接mongodb
* @param callback
*/
function connection(callback){
if(!db){
var dbConfig = Util.get('config.json','db');
var host = dbConfig['host']
, user = dbConfig['user']
, password = dbConfig['password']
, port = dbConfig['port']
, db_name = dbConfig['db_name']
, authSource = dbConfig['authSource'];
var url = 'mongodb://'+user+':'+password+'@'+host+':'+port+'/'+db_name+'?authSource='+authSource;
MongoClient.connect(url,function(err,dbObject){
assert.equal(null,err);
console.log('Connect to MongoDB success~');
db = dbObject;
callback(db);
});
}else{
callback(db);
}
}
}
这个是http服务器的js文件,index.js
var http=require('http')
, BaseMongodb = require('./base_mongodb')
, baseMongodb = new BaseMongodb();
http.createServer(function(req,res){
res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
switch (req.url)
{
case '/':
baseMongodb.findOneById('node_booki','5574fc1055608daf0b789f38',function(ret){
if(ret)
res.end(JSON.stringify(ret));
else
res.end('222');
});
break;
}
}).listen(3000);
console.log("浏览器打开http://127.0.0.1:3000");
为什么我http://127.0.0.1:3000刷新两次的时候第二次总是查询不了数据库然后卡住,第一次就可以~~为啥?
8 回复