Mongoose - find documents containing a link to subdocuments

I have 2 models,

var locationSchema = mongoose.Schema({
    name: String,
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }]
});

var userSchema = mongoose.Schema({
    name: String,
    email: String
});

I would like to get an entire Location that has a specific user. For example, with the following data,

Location      Users
    A         [1,2,3]
    B         [1,4,5]
    C         [6]

Let's say I want to find all locations that have user # 1. I tried to follow, didn't work

var locationModel = mongoose.model('Location', locationSchema);

locationModel.find({
    users : { $in: user }
});

locationModel.find({
    'users._id' : user._id
});

locationModel.find({
    'users.$oid' : user._id
});

locationModel.find({
    'users.id' : user._id
});

Any idea?

+4
source share
1 answer
locationModel.find({
    users : { $in: [some_user_id] }
});
+2
source

Source: https://habr.com/ru/post/1528220/


All Articles