0

So bassically I have three roles for users

  1. admin
  2. seller
  3. buyer

This is my User Scheme

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true, select: false },
  role: { type: String, enum: ['seller', 'buyer'], required: true },
  admin: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  seller: { type: mongoose.Schema.Types.ObjectId, red: 'Seller'},
  buyer: { type: mongoose.Schema.Types.ObjectId, ref: 'Buyer' },

})
userSchema.plugin(uniqueValidator)
module.exports = mongoose.model('User', userSchema)

This is my User Roles Schemas Seller Schema

const sellerUserSchema = mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  firstName: { type: String, required: true },
  lastName: { type: String },
  email: { type: String, required: true, unique: true },
  dob: { type: Date, min: '1950-01-01', max: new Date() },
})

Buyer Schema

const buyerUserSchema = mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  firstName: { type: String, required: true },
  lastName: { type: String },
  email: { type: String, required: true, unique: true },
  dob: { type: Date, min: '1950-01-01', max: new Date() },
})

Now when I do

    const usersQuery = Seller.find().populate('user').then(d=>{
        console.log('details',d)
    })

I get the correct result like I get seller data and then object of user including all details you can check the result below in screenshot

enter image description here

But When I do like

const usersQuery = User.find().populate('seller','buyer')

I am not getting any sort of seller or buyer data here is the result attached

enter image description here

So my expected result is like i get user data and inside seller or buyer object

Below is my database structure of MongoDB

Users

enter image description here

Sellers

enter image description here

And buyers collections is same like seller

Any help will be appriciated

1 Answers1

1

Since you have no reference of "seller" or "buyer" in User Schema , so you should try Aggregate Instead

User.aggregate([
  {
    $lookup: {
      from: "sellers",
      localField: "_id",
      foreignField: "user",
      as: "sellerSchemaUser"
    }
  },
  {
    $lookup: {
      from: "buyers",
      localField: "_id",
      foreignField: "user",
      as: "buyerSchemaUser"
    }
  }
])

As I can see from your screenshot , your "seller" Collection not yet has any document in it , so you will get an empty array in "sellerSchemaUser" for now. Note: Lookup will return matched Documents from other collection in form of array of objects.

  • This works but It should return a single object instead of array but I am getting the right object but inside an array And one more question. Is this a good approch to use aggregate? or I should also add reference in Users collection for sellers and buyers? – Arslan Malik Dec 04 '22 at 16:52
  • Lokup return array , so I really think you should learn " lookup" , "unwind". you can refer to this link for unwind [link](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/) , ` { $unwind:{path: "$sellerSchemaUser", preserveNullAndEmptyArrays: true}} ,{$unwind:{path: "$buyerSchemaUser",preserveNullAndEmptyArrays: true}} ,` Put these lines of code inside aggregate pipeline .Aggrgeate are slower but are very helpful in case of complex queries. You can add reference to sellers and buyers in case of one to one relation, it will make things easy for you. – Sudhansu Singh Dec 05 '22 at 06:43
  • Alright I understand so for approach related to saving reference in Users collection . First save user data then after saving we get _id for User after that save seller data and add _useridobject in seller then again reupdate user and update it with _sellerobjectid. Do we have any solution for this like in this scenerio first save user data without selleridobject becuade initially we dont have id of seller object before creating its data like we need 3 steps . Do we have any solution to reduce it to only 2 steps? Like if we can give our own id to seller to know the id in advance for seller? – Arslan Malik Dec 05 '22 at 09:45