所以我尝试通过将用户在用户模型中的角色从用户改为教练来让用户成为教练。
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const UserSchema = new Schema({
firstname : {
type : String,
required : true
},
lastname : {
type : String,
required : true
},
email : {
type : String,
required : true,
unique : true
},
verified : {
type : Boolean,
default : false
},
password : {
type : String,
required : true,
minLength : 3
},
role : {
type : String,
enum : ['admin', 'coach', 'user'],
default : 'user'
}
})
module.exports = mongoose.model('User', UserSchema)
下面是教练模型:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const CoachSchema = new Schema({
coach : {
type : mongoose.Schema.Types.ObjectId,
ref : 'User'
},
team : {
type : mongoose.Schema.Types.ObjectId,
ref : 'Team'
}
})
module.exports = mongoose.model('Coach', CoachSchema)
在创建新教练时,该特定用户的ID被传递到参数中,然后用户模型中的角色数据被切换到教练。教练的控制器如下所示:
const Coach = require('../models/Coach')
const User = require('../models/User')
const Team = require('../models/Teams')
exports.createCoach = async (req, res)=>{
try {
const userId = req.params.id
const coach_data = await User.findById(userId)
const {password, verified, ...other} = coach_data._doc
console.log(other);
const team = req.body.team
const team_data = await Team.findById(team)
const user = await User.findById(userId)
if(!user) return res.status(400).json({
error : 'User not found'
})
const coach = new Coach({
coach : other,
team : team_data
})
if(user.role === 'coach') return res.status(404).json({
error : 'User is already a coach'
})
const updateUser = await User.findOneAndUpdate({ _id : userId}, {
role : 'coach'
},
{
new : true
}
)
await coach.save()
res.status(200).json('User has been made coach')
} catch (error) {
console.log(error);
res.status(500).json(error)
}
}
exports.getAllCoaches = async(req, res)=>{
try {
const coaches = await Coach.find()
res.status(200).json(coaches)
} catch (error) {
res.status(500).json(error)
}
}
这是教练的路由器:
const router = require('express').Router()
const coachController = require('../controllers/coachController')
router.post('/create-coach/:id', coachController.createCoach)
router.get('/get-coaches', coachController.getAllCoaches)
module.exports = router
这是我的数据库现在的样子[[1]:https://i.stack.imgur.com/3WclF.png[1]
1条答案
按热度按时间z18hc3ub1#
建议存储对对象
mongoose
的引用,可以在查询数据时使用.populate
用数据填充此引用,如果您有一些SQL经验,它就像foreign key
。