Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to connect 3 table in mongodb and node js

in my case, I've 3 tables

  1. users table

    name: {
        type: String,
        required: [true, 'Email is required'],
        trim: true,
        lowercase: true,
    },
    role: {
        type: String,
        required: true,
        enum: ['SUPER_ADMIN', 'ROOT_STANDERD', 'COMPANY_ADMIN', 'RETAILER_ADMIN']
    },
    company: {
        type: ObjectId,
        ref: 'company',
    },
    retailer: {
        type: ObjectId,
        ref: 'retailer'
    }
    });
    
  2. Company Table

     const CompanySchema = new Schema({
     _id: String,
     name: {
         type: String,
         required: true,
         maxLength: 50,
     }})
    
  3. Retailer Table

    const CompanySchema = new Schema({
       _id: String,
       name: {
         type: String,
         required: true,
         maxLength: 50,
     },
      company: {
        type: ObjectId,
        ref: 'company',
    }})
    

Let me explain how it works: SUPER_ADMIN can create the company, retailer(it will reference by Company), and user (if the user role is COMPANY_ADMIN then the user is referenced by company, and if the user role is RETAILER_ADMIN then the user is the reference by retailer)

SUPER_ADMIN can view all the users

Now my query is COMPANY_ADMIN can view their related company's user and retailer's user only.

like image 593
Smit lathiya Avatar asked Dec 05 '25 15:12

Smit lathiya


1 Answers

In this case you can try customize query, you can try this

user.find({ $or: [{ retailer: { $in: [retailer_id1, retailer_id2...] } }, { company: user.company }] })
like image 65
Sahil Rana Avatar answered Dec 08 '25 04:12

Sahil Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!