mongoose 如何调用用户创建的所有产品?

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

我正在使用mongodb+moongose,我已经可以做基本的CRUD,但我有麻烦得到所有的产品是由用户创建的,我不知道如果我这样做是正确的,我试着使用它.

user_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},

比如说。

Show all products that is created by User1

ProductSchema.js
从“ Mongoose ”引进 Mongoose

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)

UserSchema.js

import mongoose from 'mongoose'

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)

Controller.js

export const getProductOfUsers = async (req,res) =>{
  try {
    const posts = await Product.find({user_id: req.user.id})
    res.status(200).json(posts)

  } catch (error) {
    res.status(404).json({message: error.message})  
  }
}

Router.js

router.get('/customerproduct', getProductOfUsers)
svgewumm

svgewumm1#

在你的controller.js.中有一个打字错误。可能没有定义req.user。只要将它改为req.body.user。

相关问题