繁体   English   中英

如何使用 node.js 从 MongoDB collections 获取数据并将其呈现为 Z0ECD11C1D7A287401D148A23BBD7

[英]How do I get data from a MongoDB collections using node.js and render it as a JSON in expess

我正在尝试使用Node从我的MongoDB中的collections数据库中获取数据,我已经成功完成了。 我唯一的问题是如何渲染从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)

我通过执行 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)

这是另一种方式:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM