Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to get single element from nested array mongoose

//This solution isn't very elegant, but it works.

const objectInNestedArray = (await Schema.findOne({
    _id: '62a5bc408a97563a666c63dd',
    nestedArray : { $elemMatch : { _id: new mongoose.Types.ObjectId(id) }}//must be ObjectId
},
{
    nestedArray: {
        "$filter": {
            "input": "$nestedArray",
            "as": "objectInNestedArray",
            "cond": { "$eq": ["$$objectInNestedArray._id", new mongoose.Types.ObjectId(id)] } //must be ObjectId
        }
    }
}))['nestedArray'][0]
 
PREVIOUS NEXT
Tagged: #single #element #nested #array #mongoose
ADD COMMENT
Topic
Name
5+9 =