如何在猫鼬中将对象字段获取为数组?

时间:2020-06-26 14:27:20

标签: node.js json mongodb mongoose

你好,我有一个如下的猫鼬模式,

const followingFollowersSchema = mongoose.Schema({
  follower: {
     type: mongoose.Schema.ObjectId,
     ref: 'User'
  },
  following: {
     type: mongoose.Schema.ObjectId,
     ref: 'User'
  },
});

我在创建路由时创建了一条路由,它过滤了当前登录用户所关注的所有用户并显示了以下输出,

{
  "status": "success",
  "results": 1,
  "data": {
    "following": [
            {
              "_id": "5ef4cd0205070d87156e19da",
              "following": {
                  "_id": "5eeb92d69fceed6d91ad5743",
                  "name": "X Y"
            }
          }
      ]
  }
}

但是我想显示这样的输出,

{
  "status": "success",
  "results": 1,
  "data": {
      "following": [
          {
              "_id": "5eeb92d69fceed6d91ad5743",
              "name": "X Y"
          }
      ]
  }
}

我该怎么做?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以使用$addFields替换现有字段,并使用$map转换内部数组:

let result = Model.aggregate([
    {
        $addFields: {
            "data.following": {
                $map: {
                    input: "$data.following",
                    in: "$$this.following"
                }
            }
        }
    }
])

Mongo Playground