Andrei Daniel
Andrei Daniel

Reputation: 181

I can't get why I have to query a MongoDB collection in a specific way (dot vs bracket notation)

So I have this mongoose schema:

let userSchema = new mongoose.Schema({
    username:
    {type: String,
    unique: true
    },
    password: String,
    privileges:
    [{
            region: Number,
            read: Number,
            write: Number,
            edit: Number
    }]
});

and I want to query the DB so I get the one with region = 1. After many tries I got it - I have to use privileges.0.region in order to get there. But I have NO idea why. click

These are all the queries I tried to make and I don't get why it doesn't work. Using my logic, privileges[0]['region'] & privileges[0].region should work because I'm selecting the first item of the array with the region property.

Can anyone explain to me the whole thing? Why don't these queries work and the one with dots works? It's very strange to me because dot notation (as far as I know) is for properties, and privileges should be an array (privileges[0], privileges[2], privileges[3] , ect) so it can't be accessed with dot notation because that's not a property. That's my logic.

Thanks.

Upvotes: 1

Views: 485

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311845

Dot notation with zero-based indexes is just the syntax they chose and square bracket syntax isn't supported. See the docs here.

Upvotes: 1

Related Questions