【问题标题】:Find specific data in MongoDB via NodeJS通过 NodeJS 在 MongoDB 中查找特定数据
【发布时间】:2019-08-31 02:11:31
【问题描述】:

我需要在我的 MongoDB 中为其余 API 查找特定数据,但它返回 null。

app.get('/api/v1/champions/:name', (req, res) => {
    db.find({"champions": req.params.name}, (err, champion) => {
        res.json(err)
    })
    })

这是我的 MongoDB 架构:

champions: {
    champ_name_1: {
        dmg: Number,
        cost: Number
    },
    champ_name_2: {
        ....
    }
}

【问题讨论】:

    标签: node.js mongodb rest


    【解决方案1】:

    由于您正在检查冠军对象中是否存在键,因此您需要以不同的方式编写查询。

    如果您的数据是这样格式化的,那么您的查询就可以工作。 (冠军是一个字符串)

    {
        "champions": "champ_name_1",
        "dmg": 123,
        "cost": 123
    }
    

    要检查 mongo 中的对象中是否存在键,请使用这样的查询。

    const champKey = 'champions.' + req.params.name;
    db.find({ [champKey]: { $exists: true } });
    

    https://docs.mongodb.com/manual/reference/operator/query/exists/

    【讨论】:

    • 编辑:我创建了一个对象来将变量传递给 db.find()。 code 让 params = {}: params[cham​​pKey} = {$exists: true}; code db.find(params)...
    【解决方案2】:

    你可以使用猫鼬包 here

    并简单地使用猫鼬的find() 方法来查找提供给它的特定数据。

    例如:find({_id: MY_ID_HERE});

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2022-07-29
      • 2015-11-08
      • 1970-01-01
      • 2022-01-22
      • 2017-12-15
      • 2017-07-19
      • 2019-12-25
      • 1970-01-01
      相关资源
      最近更新 更多