我正在尝试根据用户ID检索项目。我正在使用Postman对其进行测试,但是我无法根据用户ID成功获取商品。在邮递员中,我试图获取类似这样的项目:localhost:5000 / api / items / user id会放在这里。基本上,当输入用户ID时,应该返回与该ID相关的所有项目。
**ItemSchema Model**
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create Item Schema
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
user:{
type: Schema.Types.ObjectId,
ref:'User'
}
});
module.exports = Item = mongoose.model('Item', ItemSchema);
**UserSchema Model**
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create User Schema
const UserSchema = new Schema({
name:{
type: String,
required: true
},
title:{
type: String,
required: true
},
age:{
type: Number,
required: true
},
items:[{type: Schema.Types.ObjectId, ref: 'Item' }]
});
module.exports = User = mongoose.model('User', UserSchema);
**routes/api/items.js**
const express = require('express');
const router = express.Router();
//Items Model
const Item = require('../../models/Items');
//@Route GET api/items
//@Description GET all items
//@Access Public
router.get('/', (req, res) =>{
Item.find({user:req.body.user})
.then(items => res.json(items));
});
//@Route POST api/items
//@Description POST an item
//@Access Public
router.post('/', (req, res) =>{
const newItem = new Item ({
name: req.body.name,
user: req.body.user
});
newItem.save().then(item => res.json(item));
});
//@Route DELETE api/items/:id
//@Description DELETE an item
//@Access Public
router.delete('/:id', (req, res) =>{
Item.findById(req.params.id)
.then(item => item.remove().then(() => res.json({success: true})))
.catch(err => res.status(404).json({success: false}));
});
module.exports = router;
**routes/api/users.js**
const express = require('express');
const router = express.Router();
//User Model
const User = require('../../models/Users');
//@Route GET api/users
//@Description GET all users
//@Access public
router.get('/', (req, res) =>{
User.find()
.then(users => res.json(users));
});
//@Route POST api/users
//@Description POST a user
//@Access public
router.post('/', (req, res) =>{
const newUser = new User({
name: req.body.name,
title: req.body.title,
age: req.body.age,
items: req.body.items
});
newUser.save().then(user => res.json(user));
});
//@Route DELETE api/users/:id
//@Description DELETE a user
//@Access public
router.delete('/:id', (req, res) =>{
User.findById(req.params.id)
.then(user => user.remove().then(() => res.json({success:true})))
.catch(err => res.status(404).json({success: false}));
});
module.exports = router;