Node.js Question

Mongoose query with project and filter

i have query:

Model.aggregate([{
$lookup: {
from: 'translations',
localField: '_id',
foreignField: 'item_id',
as: 'translation'
},
}, {
$project: {
"label": "$label",
"items": "$items",
"translation": {
"$filter": {
"input": "$translation",
"as": "page",
"cond": {
"$eq": ["$$page.lang_key", lang]
}
}
}
}
}])


And result:

[ { _id: 58b2ca5b9ac42bac7aaed48a,
label: 'Main',
items: [ [Object] ],
translation: [ [Object] ] } ]


How to make so that the field
translation
was not an array?
Because i always receive only one element in Array...

Answer Source

Since you only receive one element in the array, you can either use $unwind or $arrayElemAt to flatten the array and produce a subdocument. For the latter, something like the following should work for you:

Model.aggregate([
    {
        "$lookup": {
            "from": "translations",
            "localField": "_id",
            "foreignField": "item_id",
            "as": "translation"
        }
    }, 
    {
        "$project": {
            "label": 1, "items": 1,
            "translation": {
                "$arrayElemAt": [
                    {
                        "$filter": {
                            "input": "$translation",
                            "as": "page",
                            "cond": { "$eq": ["$$page.lang_key", lang] }
                        }
                    },
                    0
                ]
            }
        }
    }
])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download