如何重命名 Mongo 查询输出中的字段?

Ste*_*ano 2 mongoose mongodb mongodb-query

我想在 MongoDB 的 mongoose 函数中转换这个 SQL 查询(我的目标是将描述转换为 desc )。

select description as desc from book
Run Code Online (Sandbox Code Playgroud)

我该如何修复这个功能?

book.find({})
    .lean()
    .exec(function(err, recs) {
       if (err) {
           console.warn(err)
       } else {
           console.log(recs);
     });
Run Code Online (Sandbox Code Playgroud)

Jyo*_*aja 5

您可以尝试在aggregation管道中进行投影

book.aggregate([
    {
        $project: {
            _id: 0,  
            'desc': '$description' //aliasing 
        }
    }
], function (err, recs) {
    if (err) {
        console.log(err);
    } else {
        console.log(recs);
    }
});
Run Code Online (Sandbox Code Playgroud)

aggregation这里阅读更多信息