简体   繁体   中英

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. My only problem is how to render the obtained data from the collections and posting it into the express app.

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.

 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));
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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