如你所见,我有两个模型 邮政
import mongoose from 'mongoose';
const PostSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
text: {
type: String,
required: true,
unique: true,
},
tags: {
type: Array,
default: [],
},
viewsCount: {
type: Number,
default: 0,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: '用户',
required: true,
},
imageUrl: String,
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
},
{
timestamps: true,
},
);
export default mongoose.model('Post', PostSchema);
用户
import exp from "constants";
import mongoose from "mongoose";
const 用户Schema = new mongoose.Schema({
fullName: {
type: String,
required:true,
},
email: {
type: String,
required:true,
unique: true,
},
passwordHash: {
type: String,
required: true,
},
role: {
type: String,
enum: ["student", "instructor"],
required: true,
},
avatarUrl: String,
},
{
timestamps: true,
});
用户Schema.methods.isStudent = function () {
return this.role == "student";
};
用户Schema.methods.isIsntructor = function () {
return this.role == "instructor ";
};
export default mongoose.model('用户', 用户Schema);
如你所见,我有两个角色,教师和学生.现在我可以得到所有的帖子
export const getAll = async(req, res) => {
try{
const posts = await PostModel.find().populate('user').exec();
res.json(posts);
} catch(err){
console.log(err);
res.status(500).json({
message: 'Can not get post',
});
}
}
但我想让所有的帖子都是由导师创建的.我如何实现这一点?
我试着像这样做铁匠
export const getAllByTeacher = async(req, res) => {
try {
const posts = await PostModel.find({role: "instuctor"}).populate('user').exec();
res.json(posts);
} catch (e) {
console.log(e);
res.status(500).json({
message: 'Can not get post'
});
}
}
但是我不知道如何从用户那里访问角色,希望你们能帮助我!我被这个问题困扰了好几天.