ZoM
ZoM

Reputation: 516

Mongoose - Find documents that contain a reference of sub-documents

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 all Location that has a specific user. For example, with following data,

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

Say, I want to find all locations that has user #1. I've tried following, 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?

Upvotes: 4

Views: 3640

Answers (1)

mpm
mpm

Reputation: 20155

locationModel.find({
    users : { $in: [some_user_id] }
});

Upvotes: 2

Related Questions