简体   繁体   中英

Best practice running queries in Node.js with MongoDB driver 3.6?

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?

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

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); } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM