【问题标题】:reshape result from mongodb重塑来自 mongodb 的结果
【发布时间】:2023-04-08 18:39:01
【问题描述】:

在我的 node.js 应用程序中,我使用 mongodb 和 mongoose 驱动程序。如何重塑 Modell.find() 操作的结果?如果我得到这样的示例文档:

{
   _id:   ObjectId(...),
   score: 14,
   time:  123
}

在我的查找操作中,我想在 .find() 的结果上添加一个索引(计数器)并重命名 _id 字段。这可能吗?

如果希望我的文档流看起来像这样:

[{
   index:   0
   player:  ObjectId // _id field renamed to player
   score:   14,
   time:    123
},
{
   index:   1
   player:  ObjectId // _id field renamed to player
   score:   6,
   time:    321
},
...
{
   index:   N
   player:  ObjectId // _id field renamed to player
   score:   1,
   time:    456
}
]

我试过了

Modell.find({}, {player: '$_id', score: 1, time: 1})
      .exec(function(err, players) {
         ...
});

但 _id 字段在生成的文档流中未重命名。这可能吗?以及如何在文档流中创建文档计数器。

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    .find() 方法不会进行这种重命名。为此,您需要聚合框架和 $project 运算符。

    文档上的索引号完全是另一回事,即使我不明白为什么你需要它,因为这些“索引”值已经可以访问“数组”,但你会在“之后”更改结果已从服务器检索。

    Model.aggregate(
        [
            { "$project": {
                "_id": 0,
                "player": "$_id",
                "score": 1,
                "time": 1,
            }},
        ],
        function(err,results) {
            if (err) throw err;
    
            results = results.map(function(x,index) { x.index = index; return x; });
            console.log(results);
        }
    );
    

    实际上,如果您只想返回整个结果,则可以使用 map 完成所有操作:

    Model.find({},function(err,result) {
        if (err) throw err;
    
        results = results.map(function(x,index) { 
            x.index = index;
            x.player = x._id;
            delete x._id;
            return x; 
        });
    
        console.log(results);
    });
    

    【讨论】:

    • 如果我需要一个总体搜索查询,我应该把我的搜索查询放在哪里?同 Model.find( {score: 10} ) ...
    • 参见文档中的$match。真的,您可以使用 find even 并重塑整个结果。您不会担心在这里迭代光标。
    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2018-09-18
    相关资源
    最近更新 更多