mongoose 如何调用数据引用给用户?

c9qzyr3d  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(147)

我遇到了很多麻烦,如何呈现引用到user的所有产品?我尝试做的是,使用户成为产品的所有者,这样当我获取所有表时,我将只接收由用户/所有者创建的产品

这就是我调用的方式,我不知道应该使用什么函数,

  1. router.get('/customerproduct', async (req,res) =>{
  2. try {
  3. const posts = await Product.find()
  4. .populate("user_id")
  5. res.status(200).json(posts)
  6. } catch (error) {
  7. res.status(404).json({message: error.message})
  8. }
  9. })

结构描述

  1. const ProductSchema = mongoose.Schema({
  2. user_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
  3. title: {type: String},
  4. description: {type: String},
  5. categories: {type: Array},
  6. price: {type: Number},
  7. productImage: {type: String}
  8. },
  9. { timestamps: { createdAt: true } }
  10. )
  11. export default mongoose.model('Product', ProductSchema)
eoigrqb6

eoigrqb61#

你在这里做的事情有点不对...
从输入HTTP请求中获取user_id,然后使用find运算符进行查询。
示例:
输入请求:/customerproduct/23 ww 4f 34534534 srdfr 345(仅查询随机用户ID)
API代码:

  1. router.get('/customerproduct/:user_id', async (req,res) =>{
  2. try {
  3. const { user_id } = req.params;
  4. const posts = await Product.find({user_id})
  5. res.status(200).json(posts)
  6. } catch (error) {
  7. res.status(404).json({message: error.message})
  8. }
  9. })

这将查找user_id为以下值的产品:**2016年12月23日星期四
希望这对你有帮助,谢谢。

展开查看全部

相关问题