Preview:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  { timestamps: true }
);

module.exports = User = mongoose.model("User", userSchema);


// @routes  GET api/user/stats
// @desc    Get how many users are registered with in a year/month/week
// @access  Private - Admin
router.get("/stats", isAuthenticatedAndAdmin, async (req, res) => {
  User.aggregate([
    // { $match: { createdAt: { $gte: currentYear } } },
    {
      $project: {
        year: { $year: "$createdAt" },
        month: { $month: "$createdAt" },
        week: { $week: "$createdAt" },
      },
    },
    {
      $group: {
        _id: { year: "$year", month: "$month", week: "$week" },
        count: { $sum: 1 },
      },
    },
  ])
    .then((userStats) => res.status(200).json(userStats))
    .catch((err) => res.status(500).json(err));
});
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter