首页 > 解决方案 > findOne() 查询在 mongo 控制台上运行良好,但相同的查询在我的 node.js 代码中没有返回任何内容

问题描述

我正在开发一个带有 mongo 数据库和 node.js 的简单问答系统。

如果用户发送一个预期的问题,系统应该找到它并给出一个相关的答案。

我在 mongo 控制台中尝试查询的第一个操作是:

db.answers.findOne({"question": "theQuestion"})

此查询返回与该问题匹配的文档。

当我从 node.js 尝试相同的查询时,没有响应。

MongoClient.connect(MONGO_PATH, function (err, client) {
        let db = client.db("fierobot");

        db.collection("answers").findOne({
            question: "theQuestion"
        }, function (error, response) {
            if (error)
                throw error;
            if (response)
                console.log(response);
            else
                console.log("NO RESPONSE"); // <-- I always get this
        });
    });

这是我应该收到的:

{
        "_id" : ObjectId("5d27211a8bd7a75659148866"),
        "question" : "theQuestion",
        "answer" : "theAnswer"
}

标签: node.jsmongodb-query

解决方案


MongoClient.connect(MONGO_PATH, function (err, client) {
        let db = client.db("fierobot");

        db.collection("answers").findOne({
            question: { $eq: "theQuestion" }
        }, function (error, response) {
            if (error)
                throw error;
            if (response)
                console.log(response);
            else
                console.log("NO RESPONSE"); // <-- I always get this
        });
    });

推荐阅读