在您的数据模型中设置一个布尔字段,该字段具有关键教师(或学生,如果您愿意),并在用户注册时设置。
编辑:
您可以有两种不同的架构,一种用于每种用户类型。声明它们看起来像这样。
const usersSchema = new Schema({/* base schema */});
const teachersSchema = new Schema({ /* teachers schema */});
const studentsSchema = new Schema({ /* students schema */});
和
const User = mongoose.model('User', usersSchema, 'users');
User.Teacher = mongoose.model('Teacher', teachersSchema, 'users');
User.Student = mongoose.model('Student', studentsSchema, 'users');
查看文档here
编辑 2:
我发现一个更好的方法是使用鉴别器...谢谢!
const options = {discriminatorKey: 'kind'};
const userSchema = new mongoose.Schema({/* user schema */}, options);
const User = mongoose.model('User', userSchema);
// Schema that inherits from User
const teacherSchema = User.discriminator('Teacher',
new mongoose.Schema({/* Schema specific to teacher */}, options));
const studentSchema = User.discriminator('Student',
new mongoose.Schema({/* Schema specific to student */}, options));
const teacher = new Teacher({/* you can add everything here! */});
const student = new Student({/* you can add everything here! */});
通过调用教师或学生查找
现在您有了一个带有两个 Schema 的模型!更多信息请参阅文档here.
编辑更多信息:
您将创建两种类型的数据结构,教师和学生,它们都将保存在 User 集合中。当您调用数据库时,您使用教师或学生调用。
任何对两者通用的数据都放在用户架构中,而任何特定的数据都放在相关架构中。
当您收到对 api 的调用时,您会直接进行相关查找。您可以在请求参数中使用布尔值或字符串,然后使用 if 语句或 switch 语句分隔逻辑。我会使用一个字符串和一个开关。
在您的客户端中设置两个常量 TEACHER = 'teacher'、STUDENT = 'student',并使用相关常量调用请求正文中的 api。这样,当它到达 api 时,请求将被解析为正确的查找并发回相关数据。