使用nodejs的MongoClient连接
问题描述:
我想用nodejs连接到mongodb。我想连接到一次MongoDB并使用需要的实例。使用nodejs的MongoClient连接
connection.js文件
var MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
module.export = mongoClient;
我要访问其他文件MongoClient对象执行类似操作分贝:
router.js文件
var mongoClient = require('./connection.js')
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
db1.collection('Persons', function (err, collection) {
collection.find().toArray(function(err, items) {
if(err) throw err;
console.log(items);
});
mongoClient.close();
});
我我得到以下错误:
TypeError: mongoClient.open is not a function
答
用于连接到MongoDB的,在你的NodeJS可以这样做
var MongoClient = require('mongodb').MongoClient,
async = require('async'),
datastore = {};
function connect() {
return new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://host:port/dbname', function(err, db) {
if (err)
return reject(err);
// Create required collections and set indexes
async.eachLimit(collections, 1, function(collection, cb) {
db.collection(collection).createIndex(indexes, function(error) {
if (error)
return cb(error);
return cb();
})
}, function(error) {
if (error) {
console.error('Error creating indexes on Mongodb:', error.message);
return reject(error);
}
// export db
datastore = db;
return resolve(datastore);
});
});
});
}
connect().then(function(connectionObj) {
// use connectionObj to do DB operations
}).catch(function(error) {
console.error(error);
})
你可以找到一个样本@Mongodb Docs