William.Doyle
William.Doyle

Reputation: 79

Mongodb findOne object in array by id

Im trying to find a specific entry to my database document by the users id and the by the selected field and item. I would like the items object to be returned. This is the document structure:

{
"_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": [],
}

What I have done so far is get the users id, date and then the selected meal and item to search for. What im getting returned is the entire meal array however I only want the food items object returned.

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

What im getting returned is this:

"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"
}]

what I want is simply:

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

Upvotes: 1

Views: 4522

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

Try this:

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

dinner.$ will only return the dinner items which match the criteria, i.e where dinner.name : Meat feast stone baked pizza.

Read about $(positional) operator to know more about limiting the contents of array from query result and returning element matching the query document.

Upvotes: 6

Related Questions