Home > Enterprise >  I have issues in reverse relation in nodejs using moongose one to one relationship
I have issues in reverse relation in nodejs using moongose one to one relationship

Time:12-07

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

CodePudding user response:

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.

  • Related