Home > Back-end >  Get users who have access to circle
Get users who have access to circle

Time:09-23

I have following schema of users

const mongoose = require("mongoose");
const validator = require("validator");
const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Name is required"],
      trim: true,
    },

    email: {
      type: String,
      required: [true, "Email is required"],
      validate: validator.isEmail,
      trim: true,
    },

  },

  {
    timestamps: true,
  }
);
module.exports = userSchema;

And I have following Schema of Circle

const mongoose = require("mongoose");
const circlesSchema = new mongoose.Schema(
  {
    circleName: {
      type: String,
      required: [true, "Circle name is required"],
      trim: true,
      unique: [true, "Circle name is already exists"],
    },

    blockedUsers: [{ type: mongoose.Schema.Types.ObjectId, ref: "Users" }],
  },
  {
    timestamps: true,
  }
);
module.exports = circlesSchema;

In Circle schema there is field blockedUsers array, If users objectID is there in this array means user does not have access to this circle. Now I want to get all users with their name who have access to the circle. I am new to Mongodb and looking for working mongo query.

CodePudding user response:

You'll have to do two queries for that.

const circle = await Circle.findOne({ circleName: 'My Circle' }).select('blockedUsers').lean();

const users = await User.find({ _id: { $nin: circle.blockedUsers } }).select('name');

You could also achieve that with a single aggregation pipeline, but the maintenance cost of that outweighs the benefit.

Also, I'd recommend reading those blog posts for schema design, your current schema design will possibly break for large numbers (hundreds of thousands) of blocked users.

  • Related