【问题标题】:findOne send NULL in Nodejs [closed]findOne 在 Nodejs 中发送 NULL [关闭]
【发布时间】:2020-08-26 05:25:33
【问题描述】:

我想使用 findOne 在我的数据库中呈现产品。我在我的 url 中传递了 id,以通过其 id 查找产品。

但是,结果我得到了null

这是我的server.js 文件。

app.get('/boutique/:id', (request, reponse) => {
    mongo.connect(url, function (err, db) {
        var dbo = db.db("pool");
        var cherche_id = request.params.id;

        dbo.collection("products").findOne({id : cherche_id}, function(err, result) {
            if (err) throw err;
            console.log(result);
            reponse.render('boutique_id');

            db.close();
        });
    });
});

如果我像这样更改我的 findOne 也可以:

findOne({id : 2},

【问题讨论】:

    标签: javascript node.js database mongodb


    【解决方案1】:

    request.params.id 是一个字符串,而数据库中的 id 字段是一个数字。 MongoDB 首先比较类型,所以"2" 不等于2。您需要先将值转换为数字:

    var cherche_id = +request.params.id;
    

    编辑:unary plus operator 在这种情况下将字符串转换为数字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-10
      • 2019-05-13
      • 1970-01-01
      • 2017-07-22
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多