简体   繁体   中英

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

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

在此处输入图像描述

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

在此处输入图像描述

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

Below is my database structure of MongoDB

Users

在此处输入图像描述

Sellers

在此处输入图像描述

And buyers collections is same like seller

Any help will be appriciated

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM