我遇到了很多麻煩,如何渲染所有參考給用戶的產品?我想要做的是,讓用戶成為產品的所有者,所以當我獲取所有表時,我只會收到用戶/所有者創建的產品

我就是這樣呼叫的,不知道應該用什么函式,
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)
uj5u.com熱心網友回復:
你在這里做的有點不對...
從輸入的 HTTP 請求中獲取user_id,然后使用 find 運算子進行查詢。
例子 :
輸入請求:/customerproduct/23ww4f34534534srdfr345(僅查詢隨機用戶 ID)
介面代碼:
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})
}
})
這將找到具有 user_id 的產品:23ww4f34534534srdfr345
希望這對你有幫助,謝謝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516548.html
上一篇:使用pm2部署多個實體時,NodeJSpassport-saml身份驗證失敗并顯示“預檢請求未通過訪問控制檢查”
下一篇:Node.js如何處理并發?
