【问题标题】:$AddFields adding Array instead of Single Value$AddFields 添加数组而不是单值
【发布时间】:2020-09-27 16:16:32
【问题描述】:

我正在使用以下代码,其中 soft_id 字段是根据购买对象中的 software 值添加的,但不幸的是,它通过获取所有现有软件的 id 添加了一个数组。

const user = await User.aggregate()
        .match({ _id: ObjectId(id) })                       
        .addFields({                
            'purchased.soft_id': '$purchased.software'
        })

    res.send(user);

这是我使用上述代码后得到的输出。

{
    "_id": "5f6f71685c370b1bec3763fc",
    "role": "user",
    "email": "ab137@12345.com",
    "password": "test123",
    "purchased": [
        {
            "software": "5f6e47eb92d318037c0a6e50",
            "expiredAt": "1970-01-19T12:32:40.241Z",
            "soft_id": [
                "5f6e47eb92d318037c0a6e50",
                "5f5d410d61fea800f01d8714",
                "5f6f804490b35a0398c64cd5"
            ]
        },
        {
            "software": "5f5d410d61fea800f01d8714",
            "expiredAt": "1970-01-19T12:32:40.241Z",
            "soft_id": [
                "5f6e47eb92d318037c0a6e50",
                "5f5d410d61fea800f01d8714",
                "5f6f804490b35a0398c64cd5"
            ]
        },
        {
            "software": "5f6f804490b35a0398c64cd5",
            "expiredAt": "1970-01-19T12:32:40.241Z",
            "soft_id": [
                "5f6e47eb92d318037c0a6e50",
                "5f5d410d61fea800f01d8714",
                "5f6f804490b35a0398c64cd5"
            ]
        }
    ],
    "createdAt": "2020-09-26T16:50:48.872Z",
    "updatedAt": "2020-09-26T17:54:19.208Z",
    "__v": 0
}
]

【问题讨论】:

    标签: mongoose mongodb-query aggregation-framework


    【解决方案1】:

    不能直接访问对象元素的数组,需要用到一些数组操作符,比如$map

    • $map 迭代循环,并添加新字段soft_id 值为software 并使用$mergeObjects 合并对象,
    const user = await User.aggregate()
        .match({ _id: ObjectId(id) })                       
        .addFields({                
            purchased: {
                $map: {
                    input: "$purchased",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { soft_id: "$$this.software" }
                        ]
                    }
                }
            }
        });
    
        res.send(user);
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2020-10-05
      • 1970-01-01
      • 2021-01-23
      • 2015-05-08
      • 2018-05-29
      • 1970-01-01
      相关资源
      最近更新 更多