繁体   English   中英

Mongodb:在嵌套数组属性中查找ids $

[英]Mongodb: Find ids $in nested array property

我在mongodb中为用户提供以下数据结构:

{
    _id: "someId",
    profile: {
        username: "oliv",
        friendRequests: [
            { fromUserId: "anId", accepted: false, created: "someDate"},
            { fromUserId: "otherId", accepted: true, created: "otherDate"}
        ]
}

我想检索登录的用户的friendsRequested中引用的用户对象 所以我尝试了这样的事情:

Meteor.users.find({_id: {$in: Meteor.user().profile.friendRequests.fromUserId}});
// FYI: Meteor.users is the collection and Meteor.user() retrieves the current user

但这不起作用。 我假设这是因为嵌套数组。
有什么方法可以告诉mongo通过fromUserId进行迭代吗?

谢谢

将查询更改为:

Meteor.users.find({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }});

推理:

friendRequests是一个对象数组,$ in要一个字符串数组(id),使用_.pluck可以传递对象数组,并告诉_仅针对该数组中的每个对象返回fromUserId的字段。

评论中的问题(“如果我只想从“ accepted”为假的朋友请求中获取ID,该怎么办?):

_.pluck(
    _.filter(Meteor.user().profile.friendRequests, function (req) {
        return !req.accepted;
    }),
    'fromUserid'
);

下划线过滤器文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM