简体   繁体   中英

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?

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

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