您如何从服务器上的集合中获取多条信息? [英] How do you get multiple pieces of information out of a collection on a server?

查看:38
本文介绍了您如何从服务器上的集合中获取多条信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的一些代码

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

}

这让我回到了控制台中的 {"readyState":1} .

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.

推荐答案

使用 express get 路由采用以下形式:

Using the express the get route takes the form:

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

您要在浏览器中的以下位置显示一组MongoDB集合文档(快递服务器正在侦听端口3000): http://localhost:3000/get

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

这篇关于您如何从服务器上的集合中获取多条信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆