【问题标题】:How do you get multiple pieces of information out of a collection on a server?如何从服务器上的集合中获取多条信息?
【发布时间】:2020-07-21 15:42:04
【问题描述】:

这是我的一些代码

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}

无论我尝试什么,它都会给我不同类型的错误。 我没有问题将数据保存到集合中,但尽快 当我去把它拿出来时,没有任何效果。

【问题讨论】:

  • 或许你可以试试 async/await(with driver v3) 并参考find documentation。另外请提及您正在使用的mongodb驱动api版本,因为v2和v3差异很大。
  • 使用Promise 而不是callback

标签: javascript arrays node.js mongodb express


【解决方案1】:

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

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

您想在浏览器中显示一组 MongoDB 集合文档(快递服务器正在监听 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()
        } )
    } )               
} );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多