【发布时间】:2019-06-24 01:33:33
【问题描述】:
我正在尝试通过以下查询使用 Mongoose find():
let users = await models.users.find({
inv: { $elemMatch: { name: "Some Item", name: "Another Item" } }
});
应该找到这些文件:
{
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 }]
}
但这些不应该:
{
inv: [{ name: "Different Item", amount: 1 }]
}
//and
{
inv: []
}
这适用于常规 MongoDB 查询,但对于 Mongoose,这是一个问题,因为您不能在 JavaScript 对象中拥有多个相同的属性(在这种情况下为 name 和 name)。我该如何处理?
【问题讨论】:
-
可能您正在寻找
$or查询运算符。db.collection.find({ inv: { $elemMatch: { "$or": [ { name: "Some Item" }, { name: "Another Item" } ] } } }) -
@AnthonyWinzlet 是的,这行得通,谢谢!请将其转换为答案,以便我将其标记为正确。
标签: arrays node.js mongodb mongoose