繁体   English   中英

过滤 mongodb 和 nodejs 中的文档

[英]Filtering documents in mongodb and nodejs

数据库中的数据存储如下。 如果我做这样的查询

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中有这个controller,它从数据库中获取食物营养

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 查询语法,只过滤数据库中名称与来自客户端的对象数组中的名称匹配的那些文档,而无需循环。 我们可以这样做吗?

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

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
}

尝试这个

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);
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM