user14849955
user14849955

Reputation:

How to Query Mongoose Nested Data? (mongoose/express)

I'm looking to query the item data from my mongoose data collection. I only need the "stocked" boolean value for the user "456" item "4", but when I query in my example, I instead receive the entire user object.

Data:

data = [{
    userId: "123",
    items: [{
        item: "2",
        stocked: false
      },
      {
        item: "3",
        stocked: true
      },
      {
        ...more items
      }
    ],
  },

  {
    userId: "456",
    items: [{
        item: "1",
        stocked: true
      },
      {
        item: "4",
        stocked: true
      },
      {
        ...more items
      }
    ],
  },

  {
    ...more users
  }
]

Route:

router.post("/example", (req, res) => {

  Data.findOne({
      userId: "456",
      "items.item": "4"
    }
  }).then((item) => {
  console.log(item) // desired: {item: "4", stocked: true}

  if (item.stocked) {
    console.log("Item is stocked!")
  }
})

})

Problem: The response is the entire user object including all items:

{
  userId: "456",
  items: [{
      item: "1",
      stocked: true
    },
    {
      item: "4",
      stocked: true
    },
    {
      ...more items
    }
  ],
},

Desired response: { item: "4", stocked: true }

Any tips or help would be appreciated!

Upvotes: 0

Views: 46

Answers (1)

Haniel Baez
Haniel Baez

Reputation: 1690

Using the aggregation pipeline you can make use of $elemMatch or $unwind.

The $elemMatch operator limits the contents of an field from the query results to contain only the first element matching the $elemMatch condition.

Data.aggregate([
 {$match: {userId: "456", "items.item": "4"}},
 {$project: { items: { $elemMatch: { "items.item": "4"} }}}
]);

OR

The $unwind will return all element that meet your criteria.

Data.aggregate([
 {$match: {userId: "456", "items.item": "4"}},
 {$unwind: "$items"},
 {$match: { "items.item": "4"} }
])

Upvotes: 0

Related Questions