node.js - 使用 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();
}
}
对我来说,这在某种程度上意味着我必须为我提出的每个数据库请求创建一个新连接。这个对吗?如果不是,那么保持各种路由的连接处于活动状态的最佳做法是什么?
解决方案
您可以使用 mongoose 设置与数据库的连接。
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true});
那么您需要定义您的模型,您将使用这些模型在您的路线中与您的数据库进行通信。
const MyModel = mongoose.model('Test', new Schema({ name: String }));
MyModel.findOne(function(error, result) { /* ... */ });
推荐阅读
- reactjs - React,图像模态(ant-design)组件没有第二次渲染
- ios - iOS 3DAnimations:旋转多个叠加视图时出现问题
- python - 在python中获取给定字符串的日期列表
- unity3d - 5赔后如何投放广告?统一安卓
- mongodb - mongodb查找具有相同键值的文档但不知道该值是什么
- java - 使用 Java 9 和更高版本替代默认包
- android - 如何为 putParcelableArrayList 使用通用列表?
- kdb - 删除无键表中多余的重复条目
- biztalk - 主机实例不断重启
- caching - 将 Hazelcast / Redis 隐藏在 REST 控制器后面是否有点矫枉过正?