簡體   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