简体   繁体   中英

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!

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

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