2

The official documentation of the Node.js Driver version 3.6 contains the following example for the .find() method:

const { MongoClient } = require("mongodb");

// Replace the uri string with your MongoDB deployment's connection string.
const uri = "mongodb+srv://<user>:<password>@<cluster-url>?w=majority";

const client = new MongoClient(uri);

async function run() {
 try {
  await client.connect();

  const database = client.db("sample_mflix");
  const collection = database.collection("movies");

  // query for movies that have a runtime less than 15 minutes
  const query = { runtime: { $lt: 15 } };

  const options = {
  // sort returned documents in ascending order by title (A->Z)
  sort: { title: 1 },
  // Include only the `title` and `imdb` fields in each returned document
  projection: { _id: 0, title: 1, imdb: 1 },
 };

 const cursor = collection.find(query, options);

 // print a message if no documents were found
 if ((await cursor.count()) === 0) {
  console.log("No documents found!");
 }

 await cursor.forEach(console.dir);
 } finally {
 await client.close();
}
}

To me this somewhat implies that I would have to create a new connection for each DB request I make. Is this correct? If not, then what is the best practise to keep the connection alive for various routes?

Patrick
  • 340
  • 2
  • 8

2 Answers2

0

You can use mongoose to set a connection with your database.

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});

then you need to define your models which you will use to communicate with your DB in your routes.

const MyModel = mongoose.model('Test', new Schema({ name: String }));

MyModel.findOne(function(error, result) { /* ... */ });

https://mongoosejs.com/docs/connections.html

Max
  • 781
  • 7
  • 19
  • You can export the model and use it in your routes. – Max Sep 16 '20 at 22:37
  • 1
    Thanks! I know about mongoose, but I am looking for a solution using the mongoDB Node.js driver. – Patrick Sep 16 '20 at 22:37
  • maybe you need to use the singleton pattern https://stackoverflow.com/questions/24547357/setting-up-singleton-connection-with-node-js-and-mongo – Max Sep 16 '20 at 22:41
  • @Patrick, did you ever work this out? I've got query that uses a number of lookups and filters. Running it with Mongoose is very slow and does a lot of look ups. Where i can write the query in mongo shell and get a result effortlessly. Plus the returned data is just being dumped via an api – user3067684 May 11 '22 at 07:55
0

It's 2022 and I stumbled upon your post because I've been running into the same issue. All the tutorials and guides I've found so far have setups that require reconnecting in order to do anything with the Database.

I found one solution from someone on github, that creates a class to create, save and check if a client connection exist. So, it only recreates a client connection if it doesn't already exist.

const MongoClient = require('mongodb').MongoClient

class MDB {
    static async getClient() {
        if (this.client) {
            return this.client
        }
        this.client = await MongoClient.connect(this.url);
        return this.client
    }
}

MDB.url='<your_connection_url>'

app.get('/yourroute', async (req, res) => {
     try {
        const client = await MDB.getClient()
        const db = client.db('your_db')
        const collection = db.collection('your_collection');
        const results =  await collection.find({}).toArray();
        res.json(results)
    } catch (error) {
        console.log('error:', error);
    }
})
skaz
  • 281
  • 2
  • 11