[英]Mongodb: Find ids $in nested array property
I have the following data structure for my users in my mongodb: 我在mongodb中为用户提供以下数据结构:
{
_id: "someId",
profile: {
username: "oliv",
friendRequests: [
{ fromUserId: "anId", accepted: false, created: "someDate"},
{ fromUserId: "otherId", accepted: true, created: "otherDate"}
]
}
I'd like to retrieve the user objects that are referenced in my logged user's friendsRequested . 我想检索登录的用户的friendsRequested中引用的用户对象 。 So I tried something like this: 所以我尝试了这样的事情:
Meteor.users.find({_id: {$in: Meteor.user().profile.friendRequests.fromUserId}});
// FYI: Meteor.users is the collection and Meteor.user() retrieves the current user
But it's not working. 但这不起作用。 I'm assuming it's because of the nested array. 我假设这是因为嵌套数组。
Is there any way of telling mongo to iterate through the fromUserId or something? 有什么方法可以告诉mongo通过fromUserId进行迭代吗?
Thanks 谢谢
Change your query to: 将查询更改为:
Meteor.users.find({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }});
Reasoning: 推理:
friendRequests
is an array of objects, and $in wants an array of strings(the ids), using _.pluck
you're able to pass an array of objects, and tell _
to only return the field fromUserId
for each object in the array. friendRequests
是一个对象数组,$ in要一个字符串数组(id),使用_.pluck
可以传递对象数组,并告诉_
仅针对该数组中的每个对象返回fromUserId
的字段。
Question in comment ("what if I only want to get the ids from friend requests where "accepted" is false?"): 评论中的问题(“如果我只想从“ accepted”为假的朋友请求中获取ID,该怎么办?):
_.pluck(
_.filter(Meteor.user().profile.friendRequests, function (req) {
return !req.accepted;
}),
'fromUserid'
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.