Mongodb通过id在数组中找到一个对象

时间:2017-04-12 13:55:26

标签: javascript node.js mongodb mongoose

我试图通过用户ID和所选字段和项目查找我的数据库文档的特定条目。我想要返回items对象。这是文档结构:

{
"_id": ObjectId("58edfea4b27fd0547375eeb4"),
"user_id": ObjectId("58d2dd4c8207c28149dbc748"),
"calories": 2000,
"date": 20170312,
"snacks": [ ],
"dinner": [
 {
  "nutrients": {
    "protein": "11.6",
    "carbs": "29.4",
    "fat": "7.9"
  },
  "servings": "75",
  "calories": 750,
  "name": "Meat feast stone baked pizza"
}, 
{
  "nutrients": {
    "protein": "6.8",
    "carbs": "54",
    "fat": "30.6"
  },
  "servings": "25",
  "calories": 550,
  "name": "Mc Coy's Cheddar and onion"
}],
"lunch": [],
"breakfast": [],
}

到目前为止,我所做的是获取用户ID,日期,然后选择要查找的餐点和项目。我返回的是整个餐阵列,但我只想要食品对象返回。

user_food.findOne({user_id : req.session.user_id, date: today},{'dinner': 'Meat feast stone baked pizza'},function(err, item){
        if(err){
            console.log("something went wrong: " + err);
            return res.status(500).send(err);
        }
        else{
            console.log(item);
            return res.status(200).send(item);
        }
    });

我回来的是:

"dinner": [
{
  "nutrients": {
    "protein": "11.6",
    "carbs": "29.4",
    "fat": "7.9"
  },
  "servings": "75",
  "calories": 750,
  "name": "Meat feast stone baked pizza"
}, 
{
  "nutrients": {
    "protein": "6.8",
    "carbs": "54",
    "fat": "30.6"
  },
  "servings": "25",
  "calories": 550,
  "name": "Mc Coy's Cheddar and onion"
}]

我想要的只是:

    {
  "nutrients": {
    "protein": "11.6",
    "carbs": "29.4",
    "fat": "7.9"
  },
  "servings": "75",
  "calories": 750,
  "name": "Meat feast stone baked pizza"
}

1 个答案:

答案 0 :(得分:4)

试试这个:

user_food.
findOne({
        user_id : req.session.user_id, 
        date: today,
        'dinner.name': 'Meat feast stone baked pizza'
    },{
        'dinner.$' : 1
},function(err, item){
    ....
});

dinner.$只返回符合条件的晚餐项目,即dinner.name : Meat feast stone baked pizza

阅读$(positional) operator以了解有关从查询结果限制数组内容以及返回与查询文档匹配的元素的更多信息。