如何在mongoose中为查询填充中的字段名设置别名

f45qwnt8  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(278)

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

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"
},

我怎么能做到呢?

相关问题