简体   繁体   中英

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

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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