我如何获取和填充订单的ID引用?我获取产品和用户的ID。然后,当我使用GET方法时,我将获得产品和用户的所有详细信息。
例如,我的数据将显示所有信息
产品A.标题B.价格c.产品图像
用户a.用户名b.StudentID
我试图使用Popate,但我认为我这样做是错误的。
export const getOrders = async (req,res) =>{
try {
const order = await Order.findOne({productId: '634e91d256326381d5716993'})
.populate()
.exec()
res.status(400).json(order)
} catch (error) {
res.status(404).json({message: error.message})
}
}
OrderSchema
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)
Product架构
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)
1条答案
按热度按时间deyfvvtc1#
您必须指定要在
.populate()
方法中填充的内容: