首页 > 解决方案 > 使用 MongoDB 驱动程序 3.6 在 Node.js 中运行查询的最佳实践?

问题描述

Node.js 驱动程序 3.6 版的官方文档包含以下 .find() 方法的示例:

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

对我来说,这在某种程度上意味着我必须为我提出的每个数据库请求创建一个新连接。这个对吗?如果不是,那么保持各种路由的连接处于活动状态的最佳做法是什么?

标签: node.jsmongodb

解决方案


您可以使用 mongoose 设置与数据库的连接。

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

那么您需要定义您的模型,您将使用这些模型在您的路线中与您的数据库进行通信。

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

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

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


推荐阅读