【问题标题】:return specific properties of array element - MongoDB/ Meteor返回数组元素的特定属性 - MongoDB/ Meteor
【发布时间】:2016-06-24 12:25:00
【问题描述】:

我在games 集合中有documents。每个文档负责保存运行游戏所需的数据。这是我的文档结构

{
    _id: 'xxx',
    players: [
            user:{} // Meteor.users object
            hand:[] //array
            scores:[]
            calls:[]
        ],
    table:[],
    status: 'some string'


}

基本上这是我的纸牌游戏(呼叫桥)的结构。现在我想要发布的是玩家将在他的浏览器(minimongo)中拥有他的hand 数据以及其他玩家user, scores, calls 字段。所以下到浏览器的订阅会是这样的。

{
    _id: 'xxx',
    players: [
            {
                user:{} // Meteor.users object
                hand:[] //array
                scores:[]
                calls:[]
            },
            {
                user:{} // Meteor.users object
                scores:[]
                calls:[]
            },
            //  2 more player's data, similar to 2nd player's data

        ],
    table:[],
    status: 'some string'


}

players.user 对象具有区分用户的_id 属性。在流星发布方法中,我们可以访问this.userId,它返回请求数据的用户ID。这意味着我想要_idthis.userId匹配的那个用户的嵌套hand数组。我希望这些解释可以帮助您编写更准确的解决方案。

【问题讨论】:

    标签: mongodb meteor mongodb-query meteor-publications


    【解决方案1】:

    您需要做的是“规范化”您的收藏。您可以做的是创建一个单独的集合来保存该数据并使用用户_id作为“键”,然后只在玩家字段中引用用户_id .例如。

    创建一个 GameStats 集合(或您想要的任何名称)

        {
    _id: '2wiowew',
    userId: 1,
    hand:[],
    scores:[],
    calls:[],
    }
    

    然后在游戏集合中

    {
        _id: 'xxx',
        players: [userId],
        table:[],
        status: 'some string'
    
    
    }
    

    所以如果要获取当前用户请求数据的内容

    GameStats.find({userId: this.userId}).hand
    

    编辑

    在某些情况下,它们确实鼓励非规范化,但在您上面发布的代码中,数组不起作用。这是来自 mongoDB 文档的示例。

    {
    _id: ObjectId("5099803df3f4948bd2f98391"),
    name: { first: "Alan", last: "Turing" },
    birth: new Date('Jun 23, 1912'),
    death: new Date('Jun 07, 1954'),
    contribs: [ "Turing machine", "Turing test", "Turingery" ],
    views : NumberLong(1250000)
    }
    

    【讨论】:

    • 感谢您的建议。由于 MongoDB 鼓励非规范化,我正在寻找与我的结构匹配的答案。 :)
    【解决方案2】:

    要从数组元素中获取特定属性,您可以编写如下行 db.games.aggregate([{$unwind:"$players"},{$project:{"players.scores":1 }}]);这只给了我们 id 和 scores 字段

    【讨论】:

    • 我认为聚合不适用于我的情况。我需要为流星发布返回一个查找光标
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多