【问题标题】:Get the field of a mongodb document from URL Node.js从 URL Node.js 获取 mongodb 文档的字段
【发布时间】:2020-10-04 04:47:16
【问题描述】:

我正在尝试创建一个 API 路由,在其中我从 URL 传递 mongodb 数据库中的字段,并且似乎该字段未正确处理,因为即使数据库具有与查询匹配的条目,我也没有得到任何结果.

网址格式如下:localhost:5000/api/animal/find/stripes/yes 一般形式:localhost:5000/api/animal/find/<FIELD>/<VALUE>

值被正确处理,但字段没有。

我执行查询的代码如下:

exports.getAttributeController = (req, res) => {
const field = req.params.field;
console.log(field); //DEBUG
const value = req.params.value
console.log(value); //DEBUG
    Animal.find({
field: value
}).exec((err, animal) => {
    if (err || !animal) {
        return res.status(400).json({
            error: 'No Animals found'
        });
    }
    res.json(animal);
});
};

如果我使用 console.log,我会看到正确的值已从 URL 发送,如果我像这样对 field 进行硬编码

 Animal.find({
'stripes': value
...

我得到一个结果,只有当我尝试插入 field 变量时,我没有得到任何结果。我怎样才能解决这个问题? 提前致谢

【问题讨论】:

    标签: node.js mongodb api express


    【解决方案1】:

    你想要评估field的值,所以你想要

    Animal.find({
      [field]: value // note the brackets that mean use the value of `field`
    }).exec((err, animal) => {
    

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2022-08-24
      • 2022-11-24
      • 2014-10-06
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多