node.js - Finding only an item in an array of arrays by value with Mongoose -
node.js - Finding only an item in an array of arrays by value with Mongoose -
here illustration of schema data:
client { menus: [{ sections: [{ items: [{ slug: 'some-thing' }] }] }] }
and trying select this:
schema.findone({ client._id: id, 'menus.sections.items.slug': 'some-thing' }).select('menus.sections.items.$').exec(function(error, docs){ console.log(docs.menus[0].sections[0].items[0].slug); });
of course of study "docs.menus[0].sections[0].items[0].slug" works if there 1 thing in each array. how can create work if there multiple items in each array without having loop through find it?
if need more details allow me know.
the aggregation framework finding things in nested arrays positional operator fail you:
class="lang-js prettyprint-override">model.aggregate( [ // match "documents" meet criteria { "$match": { "menus.sections.items.slug": "some-thing" }}, // unwind arrays de-normalize documents { "$unwind": "$menus" }, { "$unwind": "$menus.sections" }, { "$unwind": "$menus.sections.items" } // match element(s) meet criteria { "$match": { "menus.sections.items.slug": "some-thing" }} // optionally grouping nested array // 1 step @ time { "$group": { "_id": "$_id", "items": { "$push": "$menus.sections.items.slug" } }}, { "$group": { "_id": "$_id", "sections": { "$push": { "items": "$items" } } }}, { "$group": { "_id": "$_id", "menus": { "$push": { "sections": "$sections" } } }}, ], function(err,results) { } )
also see other aggregation operators such $first
keeping other fields in document when using $group
.
node.js mongodb mongoose
Comments
Post a Comment