node.js - 以 HTML 格式显示 MongoDB 集合数据
问题描述
所以我是 MongoDB 的新手。
我正在开发一个网站,我想根据该集合中的 {Name: String} 从 MongoDB 集合中获取数据,并将其显示在 HTML 表中。
这就是我所拥有的:
- 一个 Index.js 文件(服务器端 js)
- 我有一个名为 CustomersDB 的 MongoDB 集合,其中包含一些数据(文档)(我编写了将其保存在此客户集合中的代码并且它可以工作)
我需要的:
我在我的 index.js 文件中为 app.get('/customers') 编写了什么样的代码,这将允许我从集合中获取数据并将其显示在我的 customers.ejs 文件的表中。
我为此使用的语言和其他语言是:Node.js、Express、EJS、Body Parser、Cors 和 MongoDB
解决方案
您需要连接到您的集群并获得一个 MongoClient,就像您插入数据一样。然后您可以使用 find({}) 搜索集合中的所有文档。下面是一些示例代码,可帮助您入门。
const { MongoClient } = require('mongodb');
async function main() {
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
/**
* The Mongo Client you will use to interact with your database
* See https://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html for more details
*/
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
await client.connect();
await findCustomers(client);
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
async function findCustomers(client) {
// See https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#find for the find() docs
const cursor = client.db("NameOfYourDB").collection("NameOfYourCollection").find({});
// Store the results in an array. If you will have many customers, you may want to iterate
// this cursor instead of sending the results to an array. You can use Cursor's forEach()
// to do the iterating: https://mongodb.github.io/node-mongodb-native/3.3/api/Cursor.html#forEach
const results = await cursor.toArray();
// Process the results
if (results.length > 0) {
results.forEach((result, i) => {
console.log(result);
// Here you could build your html or put the results in some other data structure you want to work with
});
} else {
console.log(`No customers found`);
}
}
此代码基于我的 Node.js 快速入门系列中的代码:https: //www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-read-documents。
推荐阅读
- c++ - 如何从小于特定值的向量中获取前 3 个值?
- c# - Exception.Cannot 打印异常字符串的问题,因为 Exception.ToString() 失败
- python - 如何在 Apple M1 芯片上导入 Pandas
- css - 如何为多个 React 项目添加通用样式表存储库?
- apache2 - 在 ubuntu 20.04 上使用 vsftpd / apache2 挣扎
- c++ - 飞船操作员的clang-tidy解析错误
- scroll - ElementScrolled 事件没有被 CdkScrollable 和 mat-side-nav 触发
- ionic-framework - html中的离子http数据为空
- java - IntelliJ 无法从功能文件中找到步骤定义
- c# - 下面代码的 linq 查询是什么?