【问题标题】:Mongodb: Find ids $in nested array propertyMongodb:在嵌套数组属性中查找 ids
【发布时间】:2014-07-02 20:29:50
【问题描述】:

我的 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 之类的吗?

谢谢

【问题讨论】:

    标签: javascript arrays mongodb meteor


    【解决方案1】:

    将您的查询更改为:

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

    推理:

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

    评论中的问题(“如果我只想从“已接受”为假的朋友请求中获取 id 怎么办?”):

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

    Underscore filter docs

    【讨论】:

    • 谢谢,效果很好。如果您不介意,现在我还有一个问题:如果我只想从“已接受”为假的朋友请求中获取 ID,该怎么办?
    • 我更新了我的答案,如果你不介意接受这个答案就好了:) Underscore 是一个很棒的库。我强烈建议查看文档中的所有 Collection 函数,并真正尝试了解它们的用途以及如何使用它们。
    • 我虽然一开始可以工作,但实际上它似乎抛出了一大堆错误(不仅仅是过滤器,甚至是简单的采摘)-> 查看编辑(但感谢您答案)
    • 能否请您发布结果:console.log(JSON.stringify({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }}); 就在引发错误的行之前。
    • 嗯,那行在 return{requests: ->query } 所以我不知道该怎么做...
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2015-06-20
    • 2015-05-18
    • 2020-07-26
    • 2023-02-01
    • 1970-01-01
    • 2020-12-18
    • 2017-09-30
    相关资源
    最近更新 更多