猫鼬查找返回错误结果

时间:2021-03-13 12:16:51

标签: mongodb mongoose

我有两个架构:

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

const userLikeSchema = new Schema(
  {
    userId: {
      type: String,
      required: true,
      ref: 'User',
    },
    likedUserId: {
      type: String,
      required: true,
      ref: 'User',
    },
    isActive: {
      type: Boolean,
      required: true,
      default: true,
    },
  },
  {
    timestamps: true,
  }
);

我正在尝试获取按赞数降序排列的用户列表。 我不确定我做的类似 sql 的模式是否正确。 我编写了以下查询:

const likedUsers = await UserLike.aggregate(
      [
        {
          $group: {
            _id: '$likedUserId',
            likes: { $sum: 1 },
          },
        },
        { $sort: { likes: -1 } },
        {
          $lookup: {
            from: 'users',
            localField: 'likedUserId',
            foreignField: '_id.str',
            as: 'user',
          },
        },
      ]
    );

我试图得到如下结果:

 [
   {
      "_id": "604bb648be8680063009fddc",
      "likes": 2,
      "user": {
                "_id": "604bb648be8680063009fddc",
                "username": "muhamed",
                "password": "$2b$10$EVYWZb4vl2TFGmIrCWe1sO/QogdU6/Ui8TgujY4PMKLJKIVOzmOi6",
                "createdAt": "2021-03-12T18:43:20.806Z",
                "updatedAt": "2021-03-12T18:46:17.635Z",
                "__v": 0
               },         
    }
]

但相反,我得到以下显示每个项目的每个用户:

[
        {
            "_id": "604bb648be8680063009fddc",
            "likes": 2,
            "user": [
                {
                    "_id": "604bb648be8680063009fddc",
                    "username": "muhamed",
                    "password": "$2b$10$EVYWZb4vl2TFGmIrCWe1sO/QogdU6/Ui8TgujY4PMKLJKIVOzmOi6",
                    "createdAt": "2021-03-12T18:43:20.806Z",
                    "updatedAt": "2021-03-12T18:46:17.635Z",
                    "__v": 0
                },
                {
                    "_id": "604bc703ea4bf93fb427056a",
                    "username": "krasniqi",
                    "password": "$2b$10$dnKumHhKNIfA6BM3uekymOpIdMFuQy9aYYKmGBxnW401CjTAuMLIy",
                    "createdAt": "2021-03-12T19:54:43.368Z",
                    "updatedAt": "2021-03-12T19:54:43.368Z",
                    "__v": 0
                },
                {
                    "_id": "604c90ab9f7b970cd46ff668",
                    "username": "matin",
                    "password": "$2b$10$CEUCaGk.JF5PBwsTBE3fRufVXzUBt.eLyo28eTt8zhBezVSFflMhS",
                    "createdAt": "2021-03-13T10:15:07.877Z",
                    "updatedAt": "2021-03-13T10:15:07.877Z",
                    "__v": 0
                }
            ]
        },  
    ]

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我认为 _id.str 存在问题。

您的 userLikeSchema 设置错误。您应该已将 ID 字段的 type 设置为 mongoose.Schema.ObjectId

const userLikeSchema = new Schema(
 {
    userId: {
        type: mongoose.Schema.ObjectId,
        required: true,
        ref: 'User',
    },
    likedUserId: {
        type: mongoose.Schema.ObjectId,
        required: true,
        ref: 'User',
    },
    isActive: {
        type: Boolean,
        required: true,
        default: true,
    },
 },
 {
    timestamps: true,
 }
);

之后,您可以通过_id轻松查找:

const likedUsers = await UserLike.aggregate(
[
    {
        $group: {
            _id: '$likedUserId',
            likes: { $sum: 1 },
        },
    },
    { $sort: { likes: -1 } },
    {
        $lookup: {
            from: 'users',
            localField: '_id',
            foreignField: '_id',
            as: 'user',
        },
    }, {
        $unwind: "$user"
    }
]
);

作为 $lookup 的结果,您将获得一个 user 数组,因此您需要使用 $unwind 来获得单个 User 对象。

结果如下:

{
    "_id": "604bb648be8680063009fddc",
    "likes": 2,
    "user": {
        "_id": "604bb648be8680063009fddc",
        "username": "muhamed",
        "password": "$2b$10$EVYWZb4vl2TFGmIrCWe1sO/QogdU6/Ui8TgujY4PMKLJKIVOzmOi6",
        "createdAt": "2021-03-12T18:43:20.806Z",
        "updatedAt": "2021-03-12T18:46:17.635Z",
        "__v": 0
    },
}