我试图在查询填充后从引用字段设置别名,但我不知道如何处理它,下面是我的代码来查询数据:
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"
},
我怎么能做到呢?
1条答案
按热度按时间mrfwxfqh1#
在聚合管道like this中的$sort阶段之后使用$project阶段