简体   繁体   中英

Selecting subdocument in mongoose with a $

This is my document structure:

"event": {
    "attendants": {
        "seekers": [
            {
                "$oid": "5bcdabd27e51de001576d289"
            },
            {
                "$oid": "5bc9b39c1a48dd0d7d521924"
            },
        ],
        "employers": [
            {
                "id": {
                    "$oid": "5bcda6477e51de001576d287"
                },
                "boothVisits": []
            },
            {
                "id": {
                    "$oid": "5bd0787e0f64cd001563ddbf"
                },
                "boothVisits": [
                    {
                        "$oid": "5bcda6477e51de001576d287"
                    },
                    {
                        "$oid": "5bd0787e0f64cd001563ddbf"
                    },
                ]
            },
        ]
    },
}

I need to select events in which current user's id is in the employers table. But there is the boothVisits as well there which prevents a simple in check. This is what I tried to do

Event.find().where('attendants.employers.$.id').equals(req.user._id).catch(e => console.log(e)),

But it ain't working. What am I missing? I'm assuming I'm using the $ in a wrong way.

IF the whole document to be returned then you do not need to use $ .

Simply use as below:

const mongoose = require('mongoose');
Event.find({"attendants.employers.id": mongoose.Types.ObjectId(req.user._id)}),

This will check id under employers array if found then the whole event will be returned.

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