I'm trying to query all users that favorited an event. The event Id is stored in the users document in a nested object.
My schema looks like this
{
email: {
type: String,
unique: true,
required: [true, 'Email is required!'],
trim: true,
validate: {
validator(email) {
const emailRegex = /^[-a-z0-9%S_+]+(\.[-a-z0-9%S_+]+)*@(?:[a-z0-9-]{1,63}\.){1,125}[a-z]{2,63}$/i;
return emailRegex.test(email);
},
message: '{VALUE} is not a valid email!',
},
},
role: {
type: String,
enum: ['admin', 'user', 'planner'],
default: 'user',
},
name: {
type: String,
trim: true,
},
username: {
type: String,
trim: true,
unique: true,
},
password: {
type: String,
required: [true, 'Password is required!'],
trim: true,
minlength: [6, 'Password needs to be longer!'],
validate: {
validator(password) {
return password.length >= 6 && password.match(/\d+/g);
},
},
},
picture: {type: String},
favorites: {
events: [
{
type: Schema.Types.ObjectId,
ref: 'Event',
},
],
},
}
How would I write this query?
I've tried all kinds of combinations with $elemMatch and normal queries aswell
db.collection.find({ "favorites.events": userId })