我已经在nodejs中创建了两个模型,分别是:User
和Auth
。
在用户模型中将存储用户名和作为Auth模型引用的身份验证对象数组。
在Auth模型中,将存储JWT生成的令牌和令牌的创建日期...
规则: 每个用户可以有多个身份验证令牌,但是每个令牌在令牌过期后将是唯一的,它将在数据库中中止,但是创建日期应该保留。
我怎么了?
1)我在Array中存在转换问题。
2)我不知道如何通过身份验证令牌和特定的用户名来遍历此对象数组。
const mongoose = require('mongoose');
class AuthModel {
createSchema(){
const authSchema = new mongoose.Schema({
token: {
type: String,
unique: true,
required: true
},
createAt: {
type: Date,
default: Date.now
}
});
return authSchema;
}
}
module.exports = mongoose.model('AuthModel', new AuthModel().createSchema());
const mongoose = require('mongoose');
class UserModel {
createSchema(){
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
auth: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'AuthModel',
required: true,
}]
});
return userSchema;
}
}
module.exports = mongoose.model('UserModel', new UserModel().createSchema());
答案 0 :(得分:0)
1: //define embedded schema
const authSchema = new mongoose.Schema({
type: mongoose.Schema.Types.ObjectId,
ref: 'AuthModel',
required: true,
});
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
auth: [authSchema] // add embedded schema here
});
2 . When you fetch userModel, you will be required to populate( mongoose function) auth model