如何在猫鼬中为查询种群中的字段名设置别名



我试图在查询填充后从引用字段设置别名,但我不知道如何处理,这里是我的查询数据代码:

const postData = await postModel
.find({ author: id })
.populate('author')
.sort({ updatedAt: -1 });
console.log(postData)

插入数据库的示例数据:

{
"_id": "63636e95422ce851ec25d680",
"author": {
"_id": "6362a7313410b2941a18a559",
"username": "apple",
"fullname": "Apple",
"email": "my-example-email@gmail.com",
"createdAt": "2022-11-02T17:21:53.092Z",
"updatedAt": "2022-11-02T17:21:53.092Z"
},
"content": "hello world, i was born to say goodbye world!",
"createdAt": "2022-11-03T07:32:37.384Z",
"updatedAt": "2022-11-03T07:32:37.384Z"
},

我想从author字段设置别名,以获得如下结果:

{
"_id": "63636e95422ce851ec25d680",
"author": {
"user_id": "6362a7313410b2941a18a559",
"user_fullname": "Apple",
"user_email": "my-example-email@gmail.com",
"user_updated": "2022-11-02T17:21:53.092Z",
},
"content": "hello world, i was born to say goodbye world!",
"createdAt": "2022-11-03T07:32:37.384Z",
"updatedAt": "2022-11-03T07:32:37.384Z"
},

我该怎么做?

在聚合管道中的$sort阶段之后使用$project阶段,如以下

最新更新