【问题标题】:MongoDB find returns undefined in Node.Js codeMongoDB find 在 Node.Js 代码中返回 undefined
【发布时间】:2020-05-11 03:15:20
【问题描述】:

Express 在控制台日志中返回undefined。我想得到如下所示的数据。

app.get('/api/leaders/', async (req, res) => {
    try {
        const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true, useUnifiedTopology: true});
        const db = client.db('leaders');

        const leadersList = await db.collection('leaders').find({}).toArray(function (err, result) {
            console.log("Connected correctly to server");
            console.log(result);
        });

        res.status(200).json(leadersList);

        client.close();

    } catch (error) {
        res.status(500).json({message: 'Error connecting to db', error});
    }
})

这是我想要从数据库返回的数据:

db.leaders.find({})
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5a"), "username" : "kk", "score" : 20 }
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5b"), "username" : "mj", "score" : 18 }
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5c"), "username" : "vr", "score" : 15 }
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5d"), "username" : "mdb", "score" : "25" }

【问题讨论】:

    标签: node.js mongodb express mongodb-query


    【解决方案1】:

    您正在尝试将 .Js callbacks 与导致问题的 async-await 混合使用。试试下面的代码:

    app.get('/api/leaders/', async (req, res) => {
        let client;
        try {
            client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true, useUnifiedTopology: true});
            const db = client.db('leaders');
            console.log("Connected correctly to server");
    
            const leadersList = await db.collection('leaders').find({}).toArray();
    
            console.log('leadersList ::',leadersList);
            /** I would not recommend to open & close DB connections for each API call. Find a better way to manage DB connections */
            client.close(); 
            res.status(200).json(leadersList);
    
        } catch (error) {
            if(client){ console.log('Error at DB find operation'); client.close(); res.status(500).json({message: 'Error at DB find operation', error}); }
            res.status(500).json({message: 'Error connecting to db', error});
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-18
      • 2016-05-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多