APixel Visuals
APixel Visuals

Reputation: 1648

Mongoose $elemMatch with multiple of the same property

I'm trying to find() with Mongoose with the following query:

let users = await models.users.find({
  inv: { $elemMatch: { name: "Some Item", name: "Another Item" } }
});

These documents should be found:

{
  inv: [{ name: "Some Item", amount: 5 }]
}
//and
{
  inv: [{ name: "Another Item", amount: 15 }]
}
//and
{
  inv: [{ name: "Some Item", amount: 5 }, { name: "Another Item", amount: 15 }]
}
//and
{
inv: [{ name: "Some Item", amount: 5 }, { name: "Another Item", amount: 15 }, { name: "Different Item", amount: 1 }]
}

But these shouldn't:

{
  inv: [{ name: "Different Item", amount: 1 }]
}
//and
{
  inv: []
}

This works fine with regular MongoDB queries, but with Mongoose, this is a problem since you can't have multiple of the same properties in a JavaScript object (name and name in this case). How should I go about handling this?

Upvotes: 1

Views: 256

Answers (1)

Ashh
Ashh

Reputation: 46441

You are probably looking for $or query operator

db.collection.find({ inv: { $elemMatch: { "$or": [ { name: "Some Item" }, { name: "Another Item" } ] } } })

Upvotes: 1

Related Questions