How can I populate Ref Id to the orders?


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

a. title
b. price
c. productImage

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'})
    } catch (error) {
            res.status(404).json({message: error.message})  


    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) 


    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)


    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)

>Solution :

You have to specify what you want to populate inside the .populate() method:

await Order.findOne({productId: '634e91d256326381d5716993'})
    { path: 'productId', select: 'title price productImage' },
    { path: 'buyerId', select: 'username studentid' }

Leave a ReplyCancel reply