数据"/>
以HTML显示MongoDB集合数据
所以我是MongoDB的新手。
我正在开发一个网站,我希望基于该集合中的{Name:String}从MongoDB集合中获取数据,并将其显示在HTML表格中。
这是我所拥有的:
- 一个Index.js文件(服务器端js)
- 我有一个名为CustomersDB的MongoDB集合,其中包含一些数据(文档)(我编写了将其保存在此Customers集合中的代码,并且可以正常工作)
我需要:
我在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/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`);
}
}
更多推荐
以HTML显示MongoDB集合数据
发布评论