How can I get and populate the id ref to the order? I grab the id of the product and user. Then when I use my get method, I will get all the details of the products and users.
For example, my data will show all information
Product a. title b. price c. productImage
User a. username b. studentId
I tried to use populate, but I think I'm doing it wrong.
export const getOrders = async (req,res) =>{
try {
const order = await Order.findOne({productId: '634e91d256326381d5716993'})
.populate()
.exec()
res.status(400).json(order)
} catch (error) {
res.status(404).json({message: error.message})
}
}
OrderSchema
const OrderSchema = mongoose.Schema({
productId: {type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true},
buyerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
sellerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'}
})
export default mongoose.model('Order', OrderSchema)
ProductSchema
const ProductSchema = mongoose.Schema({
user_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
title: {type: String},
description: {type: String},
categories: {type: Array},
price: {type: Number},
productImage: {type: String}
},
{ timestamps: { createdAt: true } }
)
export default mongoose.model('Product', ProductSchema)
UserSchema
const UserSchema = mongoose.Schema({
username: {type: String, unique: true, required: true},
password: {type: String, required: true},
email: {type: String, unique: true, required: true},
studentid: {type: String, unique: true, required: true},
isAdmin:{type: Boolean, default: false},
},
{ timestamps: { createdAt: true } }
)
export default mongoose.model('User', UserSchema)
CodePudding user response:
You have to specify what you want to populate inside the .populate()
method:
await Order.findOne({productId: '634e91d256326381d5716993'})
.populate([
{ path: 'productId', select: 'title price productImage' },
{ path: 'buyerId', select: 'username studentid' }
])
.exec()