我遇到了很多麻烦,如何呈现引用到user的所有产品?我尝试做的是,使用户成为产品的所有者,这样当我获取所有表时,我将只接收由用户/所有者创建的产品
这就是我调用的方式,我不知道应该使用什么函数,
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})
}
})
结构描述
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)
1条答案
按热度按时间eoigrqb61#
你在这里做的事情有点不对...
从输入HTTP请求中获取user_id,然后使用find运算符进行查询。
示例:
输入请求:/customerproduct/23 ww 4f 34534534 srdfr 345(仅查询随机用户ID)
API代码:
这将查找user_id为以下值的产品:**2016年12月23日星期四
希望这对你有帮助,谢谢。