MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come riutilizzare la connessione mongodb tramite Promise

Ci sei quasi, ci sono solo un paio di modifiche da apportare al tuo codice:

"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');

var MongoClient = mongodb.MongoClient;
var url = 'mongodb://nidhind:[email protected]: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;
    });
  });
});