【问题标题】:Filtering documents in mongodb and nodejs在 mongodb 和 nodejs 中过滤文档
【发布时间】:2021-02-24 08:29:21
【问题描述】:

数据库中的数据存储如下。如果我进行类似的查询

const food = await Nutrition.find()

然后我得到这个回应

[
  {
    _id: 6035ff4778b1893fa5e8080f,
    name: 'apple',
    weight: 100,
    unit: 'gram',
    carbohydrates: 14,
    calories: 52,
    proteins: 0.3,
    fats: 0.2,
    __v: 0
  },
  {
    _id: 6036011437035541b0bd5e0a,
    name: 'banana',
    weight: 100,
    unit: 'gram',
    carbohydrates: 23,
    calories: 89,
    proteins: 11,
    fats: 0.39,
    __v: 0
  },
  {
    _id: 6036011437035541b0bd5e0b,
    name: 'melon',
    weight: 100,
    unit: 'gram',
    carbohydrates: 45,
    calories: 100,
    proteins: 11,
    fats: 0.39,
    __v: 0
  }
]

我在 nodejs 中有这个控制器,它从数据库中获取食物营养

const Nutrition = require('../model/nutritionalFacts')

exports.nutritionFacts = (async (req,res) =>{
    try {
        const food = await Nutrition.find()
        console.log(food);
    } catch (error) {
        console.log('Error occurred',error.message);
    }
})

现在在请求(req)中,req.body 来了

[
  { name: 'apple', id: 0, selected: true, weight: 100, unit: 'gram' },
  { name: 'banana', id: 1, selected: true, weight: 100, unit: 'gram' }
]

现在我只想从数据库中过滤那些名称与来自客户端的对象数组中的名称匹配的文档,如上所述,无需循环,只需使用 MongoDB 查询语法。我们可以这样做吗?

【问题讨论】:

    标签: node.js reactjs mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用$in operator 来实现这一点。您需要更改您的查找方法如下

    var namesArr = ["banana", "melon"];
    db.Nutrition.find({ "name" : { "$in": namesArr } })
    

    然后是上面示例的结果:

    {
            "_id" : ObjectId("60361058cce08c8b8ebe0509"),
            "name" : "banana",
            "weight" : 100,
            "unit" : "gram",
            "carbohydrates" : 23,
            "calories" : 89,
            "proteins" : 11,
            "fats" : 0.39,
            "__v" : 0
    }
    {
            "_id" : ObjectId("60361058cce08c8b8ebe050a"),
            "name" : "melon",
            "weight" : 100,
            "unit" : "gram",
            "carbohydrates" : 45,
            "calories" : 100,
            "proteins" : 11,
            "fats" : 0.39,
            "__v" : 0
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      const Nutrition = require('../model/nutritionalFacts');
      
      exports.nutritionFacts = (async (req, res) => {
        try {
      
          if (!Array.isArray(req.body.payload)) {
            throw new Error("Invalid payload!") // or whatever error message u want!
          }
      
          const names = payload.map(item => item.name); // u cannot avoid this looping of payload!
      
          const conditions = {
            name: { $in: names }
          };
      
          const food = await Nutrition.find(conditions);
          console.log(food);
        } catch (error) {
          console.log('Error occurred', error.message);
        }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-08
        • 1970-01-01
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        • 2019-03-04
        • 2011-01-09
        • 2021-09-20
        相关资源
        最近更新 更多