【发布时间】: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