0

I have this JSON which represents an apartment listing:

{
    "_id": {
        "$oid": "5673d1dcf93fe452d80c2c2c"
    },
    "street": "myStreet",
    "buildingNumber": 1,
    "apartmentNumber": 1,
    "UsersAndQuestions": [
        {
            "userID": "5673afe4cb62303816bd3d5c",
            "questionID": [
                "5669d90a058ceddc158e97e2",
                "4668d80b158ceggc158e97f2"
            ]
        }
    ]
}

I want to get the questionID array of a certain userID.

I am using this http.get to try and get it:

app.get('/api/listing/getQuestionsOfUserInListing/:userid/:listingid', function (req, res) {
        var user = req.params.userid;
        var listing = req.params.listingid;
        Listing.find({
                $and: [
                    {_id: listing},
                    {'UsersAndQuestions.userID': user}
                ]
            }
            , function (err, result) {
                res.json(result);
            });
    });

But I'm just getting back the whole JSON (exactly the one I posted in the beginning of the question).

How can I get just the
"questionID": ["5669d90a058ceddc158e97e2", "4668d80b158ceggc158e97f2"] ?

Thanks!

Idos
  • 15,053
  • 14
  • 60
  • 75

1 Answers1

1

As mentioned here you can do it with such projection:

Listing.findOne( {_id: listing, 'UsersAndQuestions.userID': user}, 
    {_id: 0, 'UsersAndQuestions.$': 1}, 
    function (err, result) {
        res.json(result.UsersAndQuestions[0].questionID);
    });

P.S. Also I don't see any reason why you need to use $and operator here. From documentation:

A compound query can specify conditions for more than one field in the collection’s documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.

Community
  • 1
  • 1
Volodymyr Synytskyi
  • 3,885
  • 1
  • 15
  • 19