gpt4 book ai didi

javascript - 使用 $or 在 mongoose 中复杂的多个查询

转载 作者:可可西里 更新时间:2023-11-01 09:59:06 24 4
gpt4 key购买 nike

我正在尝试找到一种方法,让自己尽可能干净地使用多个复杂查询的代码。

我在 MongoDB 中有 2 个文档。第一个是关注者,第二个是事件。

第一个查询:获取特定用户的所有关注者。第二个查询:获取所有关注者的所有事件并按日期排序。

我不知道如何进行第二个查询。

也许是这样的:

Event.find({ "$or" : [
{
'userId': followers[0].id,
},
{
'userId': followers[1].id,
},
{
'userId': followers[2].id,
},
]});

但我觉得这不是一个非常干净的代码。

最佳答案

我认为您需要的是 $in运算符(operator)。 $in运算符只取一个索引,而 $or运算符需要更多(每个子句一个)。 documentation还明确指出:

When using $or with that are equality checks for the value of the same field, use the $in operator instead of the $or operator.

您可以按如下方式修改您的查询:

var userIds = [followers[0].id, followers[1].id, followers[2].id]; 
Event.find({ 'userId': { $in: userIds } }, function(err, result){ ... });

或者如 Neil Lunn 所建议的那样,另一种解决方法是使用 native map 方法生成所需用户 ID 的数组:

Event.find({
"userId": {
"$in": followers.map(function (follower){
return follower.id
}))
}
}, function(err, result){ ... });

关于javascript - 使用 $or 在 mongoose 中复杂的多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28852745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com