Mongoose $AddFields添加数组而不是单个值

Mongoose $AddFields添加数组而不是单个值,mongoose,mongodb-query,aggregation-framework,Mongoose,Mongodb Query,Aggregation Framework,我使用以下代码,其中根据购买对象中的软件值添加soft_id字段,但不幸的是,它通过获取所有现有软件的id添加了一个数组 const user = await User.aggregate() .match({ _id: ObjectId(id) }) .addFields({ 'purchased.soft_id': '$purchased.software'

我使用以下代码,其中根据购买对象中的
软件
值添加
soft_id
字段,但不幸的是,它通过获取所有现有软件的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
}
]

它无法访问对象元素的直接数组,您需要使用一些数组运算符,如
$map

  • $map
    迭代循环,添加新字段
    soft\u 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);