我想重用MongoDB连接。我知道How to reuse mongodb connection in node.js 我想使用Promises和Mongo驱动程序v2
来实现相同的目标目前我必须为每个请求连接到db,这使得它变慢。这是我的代码
"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
//Actually I 'am connecting to MongoLab
var url = 'mongodb://localhost/my-mongo';
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function () {
console.log('ParkMe app is running on port', app.get('port'));
});
app.get('/location/create', function(req,res,next){
MongoClient.connect(url).then(function(db) {
return db.collection('parkme_parkingLots').find({}).toArray().then(function (docs) {
return docs;
});
});
});
我想做类似的事情:
"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://nidhind:1234@ds051635.mongolab.com:51635/my-mongo';
var db = MongoClient.connect(url).then(function(db) {
return db;
});
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function () {
console.log('ParkMe app is running on port', app.get('port'));
});
app.get('/location/create', function(req,res,next){
db.collection('parkme_parkingLots').find({}).toArray().then(function (docs) {
return docs;
});
});
答案 0 :(得分:6)
你几乎就在那里,你的代码中只有一些变化:
"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://nidhind:1234@ds051635.mongolab.com:51635/my-mongo';
// no need to call then() yet
var connection = MongoClient.connect(url);
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('ParkMe app is running on port', app.get('port'));
});
app.get('/location/create', function(req, res, next) {
// the connection is opened once, use it at will
connection.then(function(db) {
db.collection('parkme_parkingLots').find({}).toArray().then(function(docs) {
return docs;
});
});
});
答案 1 :(得分:1)
以下是我如何使用当代语法进行的。
我在代码中添加了一些注释。
./分贝/ mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password@localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./ index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test@dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./用户/ index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (error) {
throw error
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (error) {
throw error
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (error) {
throw error
}
}
// Export garbage as methods on the User object
module.exports = { createUser, getUsers, findUserById }