英文:
How do I access user roles to get all instructor posts in my MERN app?
问题
Here is the translated code:
正如您所看到的,我有2个模型
Post
```javascript
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: 'User',
required: true,
},
imageUrl: String,
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
},
{
timestamps: true,
},
);
export default mongoose.model('Post', PostSchema);
User
import exp from "constants";
import mongoose from "mongoose";
const UserSchema = 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,
});
UserSchema.methods.isStudent = function () {
return this.role == "student";
};
UserSchema.methods.isIsntructor = function () {
return this.role == "instructor ";
};
export default mongoose.model('User', UserSchema);
正如您所看到的,我有2个角色,instructor和student。现在我可以获取所有的帖子
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: '无法获取帖子',
});
}
}
但是我想获取所有由教师创建的帖子。我该如何实现这一点?
我尝试做类似这样的事情
export const getAllByTeacher = async(req, res) => {
try {
const posts = await PostModel.find({role: "instructor"}).populate('user').exec();
res.json(posts);
} catch (e) {
console.log(e);
res.status(500).json({
message: '无法获取帖子'
});
}
}
但我不知道如何从用户中访问角色,希望你们能帮助我!我在这个问题上卡了好几天。
Note: I've translated the code for you, but it's important to point out that there is an issue in your code logic. The "role" property is in the User model, not in the Post model, so you can't filter posts by "instructor" directly. You'll need to first find users with the role "instructor" and then find their posts.
<details>
<summary>英文:</summary>
As you can see I have 2 models
Post
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: 'User',
required: true,
},
imageUrl: String,
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
},
{
timestamps: true,
},
);
export default mongoose.model('Post', PostSchema);
User
import exp from "constants";
import mongoose from "mongoose";
const UserSchema = 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,
});
UserSchema.methods.isStudent = function () {
return this.role == "student";
};
UserSchema.methods.isIsntructor = function () {
return this.role == "instructor ";
};
export default mongoose.model('User', UserSchema);
As you can see i have 2 roles, instuctor and students. Right now I can get all posts
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',
});
}
}
But i want to get all posts created by instuctors. How do i implement this?
I tried to do smth like this
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'
});
}
}
But i dont know how to access role from user, hopefully you guys can help me! Im stuck at this problem for days.
</details>
# 答案1
**得分**: 0
以下是翻译好的代码部分:
首先,您需要获取具有教师角色的用户,然后可以使用这些信息获取由这些教师创建的帖子列表。
类似这样的代码可以工作。
```javascript
export const getAllByTeacher = async (req, res) => {
try {
const instructors = [];
const users = await UserModel.find({ role: "instructor" });
users.map(u => {
instructors.push(u._id);
});
const posts = await PostModel.find({ user: { $in: instructors } }).populate('user').exec();
res.json(posts);
} catch (err) {
console.log(err);
res.status(500).json({
message: '无法获取帖子',
});
}
}
请注意,此代码用于获取教师创建的帖子列表。
英文:
You need to first get users with instructor role and then you can use that info to get the list of posts created by those instructors.
Something like this would work.
export const getAllByTeacher = async(req, res) => {
try {
const instructors = [];
const users = await UserModel.find({ role: "instructor" });
users.map(u => {
instructors.push(u._id);
});
const posts = await PostModel.find({ user: {$in: instructors} }).populate('user').exec();
res.json(posts);
} catch (err) {
console.log(err);
res.status(500).json({
message: 'Can not get post',
});
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论