1

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
  • 296
  • 2
  • 8

1 Answers1

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
  • 741
  • 6
  • 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