[英]How do I get data from a MongoDB collections using node.js and render it as a JSON in expess
I'm trying to get data from a collections
database in my MongoDB
using Node
, which I've done successfully.我正在尝试使用
Node
从我的MongoDB
中的collections
数据库中获取数据,我已经成功完成了。 My only problem is how to render the obtained data from the collections
and posting it into the express
app.我唯一的问题是如何渲染从
collections
获得的数据并将其发布到express
应用程序中。
const { MongoClient } = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>@movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close()
})
})
}
main().catch(console.error)
I solved my own problem by just performing an app.get() in the part were it says Mongoclient.connect() and the rest is done by logic, it displays now in the express and in postman as well.我通过执行 app.get() 解决了我自己的问题,如果它说 Mongoclient.connect() 和 rest 是由逻辑完成的,它现在显示在 express 和 postman 中。
const {MongoClient} = require('mongodb'); const express = require("express"); const app = express() async function main() { const uri = "mongodb+srv://dbUser1:<password>@movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); MongoClient.connect(uri, function(err, db) { if (err) throw err; let dbo = db.db("Movies"); dbo.collection("Movies").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); app.get("/", (req, res) => {res.json(result)}) db.close() }) }) app.listen(4000, function() { console.log("listening to port 4000) } main().catch(console.error)
Here is another way:这是另一种方式:
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const app = express();
const url = 'mongodb://localhost:27017';
const dbName = 'test';
const port = 3000;
app.listen(port);
// Type this in your browser to see db data: http://localhost:3000/
app.get('/', function(req, res) {
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(function(err) {
console.log("Connected to server.");
const db = client.db(dbName);
db.collection("books")
.find({})
.toArray(function(err, result) {
if (err) throw err;
client.close();
console.log("Done reading db.");
res.send(JSON.stringify(result));
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.