簡體   English   中英

如何使用 mongoose 從字符串數組中的 object 數組返回字段

[英]How to use mongoose to return field from object array in string array

我在 mongoose 中有一個查詢,它返回:

{
    some_keys: "some values", 
    objs:[
        {name:"name1"}, 
        {name:"name2"} 
    ] 
}

我想以這種格式返回:

{ 
    some_keys: "some values",
    objs:[
        "name1", 
        "name2" 
    ] 
}

使用$map運算符循環遍歷objs數組並僅返回每個obj歸檔的name的值。

嘗試這個:

const result = await testSchema.aggregate([
    {
        $addFields: {
            objs: {
                $map: {
                    input: "$objs",
                    as: "obj",
                    in: "$$obj.name"
                }
            }
        }
    }
]);

Output

{
    "_id" : ObjectId("..."),
    "some_keys" : "some values",
    "objs" : [
        "name1",
        "name2"
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM