javascript - How to reuse mongodb connection through Promise -
i want reuse mongodb connection. 'am aware of how reuse mongodb connection in node.js want acheive same using promises , mongo driver v2
currently have connect db every request makes slow. code
"use strict" var app = require('./utils/express')(); var mongodb = require('mongodb'); var mongoclient = mongodb.mongoclient; //actually 'am connecting mongolab var url = 'mongodb://localhost/my-mongo'; app.set('port', (process.env.port || 5000)); app.listen(app.get('port'), function () { console.log('parkme app 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; }); }); });
i want like:
"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 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; }); });
you're there, there couple of changes in code made:
"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 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 running on port', app.get('port')); }); app.get('/location/create', function(req, res, next) { // connection opened once, use @ connection.then(function(db) { db.collection('parkme_parkinglots').find({}).toarray().then(function(docs) { return docs; }); }); });
Comments
Post a Comment