[MONGOOSE] To count the unique userIds in the ReaderHistory collection after looking up articleId - fourslickz/notes GitHub Wiki

const mongoose = require('mongoose');

// Article Schema
const articleSchema = new mongoose.Schema({
  title: String,
  content: String,
  authorId: mongoose.Schema.Types.ObjectId,
  createdAt: { type: Date, default: Date.now }
});

// ReaderHistory Schema
const readerHistorySchema = new mongoose.Schema({
  readerId: mongoose.Schema.Types.ObjectId,  // Assuming readerId is the userId
  articleId: mongoose.Schema.Types.ObjectId,
  readAt: { type: Date, default: Date.now }
});

// Models
const Article = mongoose.model('Article', articleSchema);
const ReaderHistory = mongoose.model('ReaderHistory', readerHistorySchema);

async function countUniqueUsersByAuthorId(authorId) {
  try {
    // Step 1: Find articles by authorId
    const articles = await Article.find({ authorId: authorId });
    
    if (articles.length === 0) {
      console.log('No articles found for this authorId.');
      return;
    }

    // Step 2: Extract articleIds
    const articleIds = articles.map(article => article._id);

    // Step 3: Count unique readerIds in ReaderHistory based on articleIds
    const uniqueUserCount = await ReaderHistory.aggregate([
      { $match: { articleId: { $in: articleIds } } },  // Match articleIds
      { $group: { _id: "$readerId" } },                // Group by readerId (userId)
      { $count: "uniqueUserCount" }                    // Count unique readerIds
    ]);

    // Step 4: Output the result
    if (uniqueUserCount.length > 0) {
      console.log('Unique user count:', uniqueUserCount[0].uniqueUserCount);
    } else {
      console.log('No readers found for these articles.');
    }

  } catch (err) {
    console.error('Error:', err);
  }
}

const authorId = "yourAuthorIdHere"; // Replace with the actual authorId
countUniqueUsersByAuthorId(authorId);