How do you get multiple pieces of information out of a collection on a server?

旧城冷巷雨未停 提交于 2021-01-29 14:02:15

问题


Here is a bit of the code I have

server.get("/get", getCallback);

function getCallback(req,res) {
    collection.find({}).next(findCallback);
    function findCallback(err,foundRecord) {
        if (err == null) {
            console.log('FOUND: ' + foundRecord);
            return res.status(200).send(foundRecord);
        }
        else
            throw err;
    }

}

It give's me back {"readyState":1} in the console.

No matter what I try it's giving me different types of errors. I have no problem-saving data to the collection but as soon as I go to take it out nothing works.


回答1:


Using the express the get route takes the form:

server.get('/', function (req, res) {
    res.send('your response document...')
})

You want to display a set of MongoDB collection documents in the browser at (the express server is listening on port 3000): http://localhost:3000/get

// Server
const express = require('express');
const server = express();
const port = 3000;

server.listen(port, () => console.log('App listening on port ' + port));

// MongoDB client
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true } );

// Your get request
server.get('/get', function (req, res) {
    client.connect(function(err) {
        assert.equal(null, err)
        console.log('Connected to MongoDB server on port 27017')
        const db = client.db('test')
        const collection = db.collection('collectionName')
        collection.find({}).toArray(function(err, docs) {
            assert.equal(err, null)
            console.log('Found the following documents:')
            console.log(docs)
            res.send(docs)
            client.close()
        } )
    } )               
} );


来源:https://stackoverflow.com/questions/61114062/how-do-you-get-multiple-pieces-of-information-out-of-a-collection-on-a-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!