You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose多集合关联实现点赞计数及用户点赞状态查询

Mongoose 物品点赞统计查询实现

前置准备:Schema 定义

首先要保证三个集合的Schema字段名统一(注意你提供的ItemLikes示例中同时出现了itemId和ItemId,建议统一为小驼峰itemId避免查询错误)

// User 模型
const userSchema = new mongoose.Schema({
  id: Number,
  Name: String
});
const User = mongoose.model('User', userSchema);

// Item 模型
const itemSchema = new mongoose.Schema({
  id: Number,
  name: String
});
const Item = mongoose.model('Item', itemSchema);

// ItemLikes 模型
const itemLikesSchema = new mongoose.Schema({
  id: Number,
  isLike: Boolean,
  userId: Number,
  itemId: Number // 统一字段名
});
const ItemLikes = mongoose.model('ItemLikes', itemLikesSchema);

核心查询实现

查询需要两个入参:targetItemId(要查询的目标物品ID)、currentUserId(当前发起查询的用户ID),推荐用聚合查询一步完成,性能更高:

async function getItemLikeStats(targetItemId, currentUserId) {
  const stats = await ItemLikes.aggregate([
    // 筛选目标物品的所有点赞记录
    { $match: { itemId: targetItemId } },
    // 分组统计总点赞数,同时判断当前用户是否点赞
    {
      $group: {
        _id: null,
        totalLikes: {
          $sum: { $cond: [{ $eq: ["$isLike", true] }, 1, 0] }
        },
        isYourLike: {
          $max: {
            $cond: [
              { $and: [{ $eq: ["$userId", currentUserId] }, { $eq: ["$isLike", true] }] },
              true,
              false
            ]
          }
        }
      }
    },
    // 格式化返回字段
    {
      $project: {
        _id: 0,
        itemId: targetItemId,
        "totalLikes(true)": "$totalLikes",
        isYourLike: 1,
        userId: currentUserId
      }
    }
  ]);
  // 处理无任何点赞记录的边界情况
  return stats.length ? stats[0] : {
    itemId: targetItemId,
    "totalLikes(true)": 0,
    isYourLike: false,
    userId: currentUserId
  };
}

调用示例

查询物品ID为1、当前用户ID为1的统计数据:

const result = await getItemLikeStats(1, 1);
console.log(result);
// 输出:{ itemId: 1, 'totalLikes(true)': 2, isYourLike: true, userId: 1 }

完全匹配要求的返回格式。

性能优化建议

给ItemLikes集合的itemId和userId字段加联合索引,可大幅提升查询速度:

itemLikesSchema.index({ itemId: 1, userId: 1 });

内容的提问来源于stack exchange,提问作者Deep Mistry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 03:12:04