0

I have this HomeSchema

Schema = mongoose.Schema;


homeSchema = new Schema({
    name: { type: String, required: true},
    administrator: {type : mongoose.Schema.Types.ObjectId, ref: 'User', required: true},


users: [{ type : mongoose.Schema.Types.ObjectId, ref: 'User' }],
});

module.exports = mongoose.model('Home', homeSchema);

I want to query whether a specific user in that users array based on user._id? I know this is rather simple, but how do I do this? Do I have to use $elematch?

TradeRaider
  • 754
  • 4
  • 8
  • 21
  • 2
    Possible dupe of https://stackoverflow.com/questions/18148166/find-document-with-array-that-contains-a-specific-value – JohnnyHK Jan 05 '17 at 03:30
  • I would argue against that @JohnnyHK. I have this users: array of ObjectId's and hence I believe it is not like searching for strings? – TradeRaider Jan 05 '17 at 03:35
  • The approach is the same whether it's an array of strings or ObjectIds. In this case it would be `{users: user._id}` to find Home docs where `users` contains `user._id`. – JohnnyHK Jan 05 '17 at 03:38

1 Answers1

0

You can use $in for this. This query will search for all the userId (this should be an array) that are present in your users array in your collection. if you want some details of the users you can use populate for that.

var query = {users : {$in:userId} }
Shumi Gupta
  • 1,505
  • 2
  • 19
  • 28