猫鼬聚合并获得喜欢计数 [英] Mongoose aggregate and get likes count

查看:57
本文介绍了猫鼬聚合并获得喜欢计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于猫鼬聚合的查询.我一直在尝试分别获取用户详细信息以及喜欢和喜欢计数及其关系,但我无法成功.

I'm having a query pertaining to Mongoose aggregation. I've been trying to fetch user details along with like and love count separately and as well as its relations but I'm unable to succeed.

这是我的场景,我有一个用户表和一个反应表.用户表包含用户详细信息,反应表包含用户详细信息以及其他信息,例如谁喜欢用户.在我的模式中,它的类型是:type='like' 或 love,所以我需要获取用户详细信息以及喜欢的数量.我是 MongoDB 的新手.

Here is my scenario, I have a user table and reaction table. User table holds user details and reaction table contains user details along with additional information like who liked the user. In my schema it's type eg: type='like' or love, so I need to get user details along with number of likes. I'm new to MongoDB.

这是我的代码:

用户架构

// Importing Node packages required for schema
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const validateEmail = function(email) {
  const re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  return re.test(email)
};
//= ===============================
// User Schema
//= ===============================
const UserSchema = new Schema({
  email: {
    type: String,
    trim: true,
    lowercase: true,
  },
  reactions : [
    { type: Schema.Types.ObjectId, ref: 'ProfileReaction' }
  ],
},
  {
    timestamps: true
  }
);


module.exports = mongoose.model('User', UserSchema);

反应模式

const mongoose = require('mongoose'),
  Schema = mongoose.Schema;

  const ProfileReactionSchema = new Schema({
    likedBy: { 
      type: Schema.Types.ObjectId, 
      ref: 'User',
      required: true,
      index: true
    },
    user: { 
        type: Schema.Types.ObjectId, 
        ref: 'User',
        required: true,
        index: true
      },
    type: {
      type: String,
      required: true,
    },
  },
    {
      timestamps: true // Saves createdAt and updatedAt as dates. createdAt will be our timestamp.
    }
);

  module.exports = mongoose.model('ProfileReaction', ProfileReactionSchema);

我真正想要的是下面的东西

What I really want is something like below

{
   _id: '1234',
   email: 'xyz@gmail.com',
   reactions: [
      {
         _id: '1235',
         likedBy: {...},
         user: {...},
         type: 'like'
      },
      {
         _id: '1236',
         likedBy: {...},
         user: {...},
         type: 'love'
      }
   ],
   noOfLikes: 1,
   noOfLoves: 1
}

到目前为止我尝试过的是,但这只是给了我关系,但我没有得到喜欢和爱的数量.但我需要他们俩都喜欢计数,喜欢计数和关系

What I've tried so far is but this is giving me only the relations but I'm not getting the count of likes and love. But I need both of them likes count, loves count and relations

const user = await User.findOne({$or: [
    req.params.id.match(/^[0-9a-fA-F]{24}$/) ? {_id: mongoose.Types.ObjectId(req.params.id)}
    : {uid: req.params.id}
    ]}).populate([
      {
        path: 'reactions',
        model: 'ProfileReaction',
        populate: [
          {
            path: 'likedBy',
            model: 'User'
          }
        ]
      }
    ]);

我使用的是 mongoose v5.6.10 版本.

推荐答案

你可以在下面使用$lookup聚合

User.aggregate([
  { "$match": {
    "$or": [
      req.params.id.match(/^[0-9a-fA-F]{24}$/)
        ? { "_id": mongoose.Types.ObjectId(req.params.id) }
        : { "uid": req.params.id }
    ]
  }},
  { "$lookup": {
    "from": ProfileReaction.collection.name,
    "let": { "reactions": "$reactions" },
    "pipeline": [
      { "$match": {
        "$expr": { "$in": ["$_id", "$$reactions"] },
        "type": "like"
      }}
    ],
    "as": "likeReactions"
  }},
  { "$lookup": {
    "from": ProfileReaction.collection.name,
    "let": { "reactions": "$reactions" },
    "pipeline": [
      { "$match": {
        "$expr": { "$in": ["$_id", "$$reactions"] },
        "type": "love"
      }}
    ],
    "as": "loveReactions"
  }},
  { "$addFields": {
    "noOfLikes": { "$size": "$likeReactions" },
    "noOfLoves": { "$size": "$loveReactions" }
  }}
])

这篇关于猫鼬聚合并获得喜欢计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆