【问题标题】:MongoDB Atlas/Cloud retrieving data from _idMongoDB Atlas/Cloud 从 _id 检索数据
【发布时间】:2021-06-12 23:16:23
【问题描述】:

我正在使用 MongoDB Atlas/Cloud 创建一个项目,并且我有方法从云中获取我创建的数据库的所有数据。

我就是这样做的:

router.get('/', (req, res) => {
    // http://localhost:3000/data
    client.connect(async err => {
        if (await err) {
            console.log("Error connecting to MongoDB Cloud:\n\t" + err.toString());
        }
        console.log("Connected to the DB!");
        const collectionData = client.db("myDatabase").collection("data");

        try {
            const data = await collectionData.find().toArray();
            console.log(data);
            res.json(data);
        } catch (e) {
            res.json({message: e});
        }

        await client.close();
    });
});

但我希望能够通过在 URI 中引入其 _id 来单独收集每个数据。这就是我尝试这样做的方式:

router.get('/:dataID', (req, res) => {
    // http://localhost:3000/data/<ID>
    client.connect(async err => {
        if (await err) {
            console.log("Error connecting to MongoDB Cloud:\n\t" + err.toString());
        }
        console.log("Connected to the DB!");
        const collectionData = client.db("myDatabase").collection("data");

        try {
            console.log(req.params.dataID); // It works, it prints the _id
            const specificData = await collectionData.findById(req.params.dataID).toArray();
            console.log(specificData);
            res.json(specificData);
        } catch (e) {
            res.json({message: e});
        }

        await client.close();
    });
});

但它不起作用。我正在检索一个空白对象:message: {}。我检查了引入的 _id,它与我试图检索的 mongoDB 对象中的 _id 完全相同。我究竟做错了什么?应该是const specificData = await collectionData.findById(req.params.dataID).toArray();,但我不知道要更改什么才能使其正常工作。

P.S.:在向服务器发送 GET 请求到/data 后,我得到了数据,但是如果我尝试在此之后再次请求,我得到一个 MongoDB 错误,有人知道为什么会这样吗?提前谢谢你

【问题讨论】:

  • 我没看错,您在每个 http 请求上都连接到 atlas 吗? Mongo 管理一个连接池,不要在必要时增加它们。在服务器启动或第一次查询到 mongo 时连接一次。空白对象message: {} 表明它来自catch(e),错误对象作为空对象被序列化为JSON。在此之前尝试console.log(e)
  • 感谢您让我意识到这一点,因为它给我带来了很多问题(速度和跳跃错误,例如“如果以前没有发生这种情况,为什么会发生这种情况?”)。这正是错误未打印的原因:TypeError: collectionData.findById is not a function

标签: node.js mongodb mongodb-query


【解决方案1】:

已解决:

const specificData = await collectionData.find(req.params.dataID).toArray();
console.log(specificData.get[0]); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-24
    • 2021-10-22
    • 2015-10-01
    • 2018-12-11
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多