Home > Net >  How to call data ref to the user?
How to call data ref to the user?

Time:10-18

I'm having a lot of trouble, How can I render all products that is Referenced to the user? What I'm trying to do is, make the user owner of the product, so when I fetch all the table, I will only receive the products created by the user/owner

enter image description here

This is how I call, and I don't know what function should I use,

 router.get('/customerproduct',  async (req,res) =>{
    try {
      const posts = await Product.find()
                    .populate("user_id")
      res.status(200).json(posts)
  
    } catch (error) {
      res.status(404).json({message: error.message})  
    }
})

Schema

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)

CodePudding user response:

You are doing things a bit wrong here...

Get the user_id from the input HTTP request and then query with find operator.

Example :

input request : /customerproduct/23ww4f34534534srdfr345 ( querying just a random user id )

API code :

 router.get('/customerproduct/:user_id',  async (req,res) =>{
    try {
      const { user_id } = req.params;
      const posts = await Product.find({user_id})
      res.status(200).json(posts)
  
    } catch (error) {
      res.status(404).json({message: error.message})  
    }
})

This will find the products having the user_id as : 23ww4f34534534srdfr345

Hope this helps you, thanks.

  • Related