So bassically I have three roles for users
- admin
- seller
- 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
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.