使用node的原生mongodb driver连接mongodb,在查文档发现,官方文档全都是通过
var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if(err) throw err;
console.log("Connected correctly to server");
//do something with db
db.close();
});
这种方式连接数据库。那么在实际项目中该怎样使用上述方式操作数据库?(在每一个路由函数中都把上述代码写一遍么= =)
备注:以前好像是使用如下方式调用数据库:
var settings = require('../settings'),
Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server;
module.exports = new Db(settings.db, new Server(settings.host, settings.port),
{safe: true});
然后在需要使用的模块
var db = require('./db');
db.open(function(err,db){
//do something
});
= =,记得这样会有堵塞的坑,所以官网开始推MongoClient,求问聚聚们,该怎么在项目中使用MongoClient呢?
暂时这样处理……