大家好,我正在尝试使用 Nest js 和 mongodb 构建 api。
我正在尝试在架构之间建立关系,当我尝试从角色填充资源时出现错误
[Nest] 12308 - 2019-08-09 4:22 PM [ExceptionsHandler] Schema hasn't been registered for model "ResourceSchema".
Use mongoose.model(name, schema) +6998ms
MissingSchemaError: Schema hasn't been registered for model "ResourceSchema".
Use mongoose.model(name, schema)
我的角色架构
import * as mongoose from 'mongoose';
import {ResourceModel} from './resourceSchema';
const Schema = mongoose.Schema;
export const RoleSchema = new Schema({
name: {
type: String,
unique: true,
required: [true, 'Role name is required'],
},
resources: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'ResourceModel',
}],
permissions: [{type: String}],
});
我的资源架构
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const ResourceSchema = new Schema({
name: {
type: String,
unique: true,
required: [true, 'Role type is required'],
},
routingInfo: {type: String},
iconName: {type: String},
iconType: {type: String},
subResources: [{type: mongoose.Schema.Types.Mixed, ref: 'ResourceModel'}],
});
export const ResourceModel = mongoose.model('Resource', ResourceSchema);
我的角色 service.ts 填充资源数组
...
@Injectable()
export class RoleService {
constructor(@InjectModel('roles') private readonly roleModel: Model<Role>) {
}
async findAll(): Promise<Role[]> {
return await this.roleModel.find().populate({path: 'resources', Model: ResourceModel});
}
// also tried that
async findAll(): Promise<Role[]> {
return await this.roleModel.find().populate({path: 'resources', Model: ResourceSchema});
}
}
我的资源模块
import {Module} from '@nestjs/common';
import {ResourcesController} from './resources.controller';
import {ResourcesService} from './resources.service';
import {MongooseModule} from '@nestjs/mongoose';
import {ResourceSchema} from '../schemas/resourceSchema';
import {ConfigService} from '../config/config.service';
import {AuthService} from '../auth/auth.service';
import {UsersService} from '../users/users.service';
import {UserSchema} from '../schemas/userSchema';
@Module({
imports: [MongooseModule.forFeature([{name: 'users', schema: UserSchema}]),
MongooseModule.forFeature([{name: 'resources', schema: ResourceSchema}])],
providers: [ResourcesService, UsersService, AuthService, ConfigService],
controllers: [ResourcesController],
exports: [ResourcesService],
})
export class ResourcesModule {
}
所以当我对 postman 执行 GET REQUEST 时,我收到该错误 任何人都可以告诉我做错了什么??????
感谢并离开
最佳答案
ResourceSchema
是架构,而不是模型。您需要注册它的模型,例如:
export const Resource = mongoose.model('Resource', ResourceSchema);
更改引用:
subResources: [{type: mongoose.Schema.Types.Mixed, ref: 'Resource'}],
他们将其导入到您的服务中并调用:
return await this.roleModel.find().populate({path: 'resources', Model: Resource });
希望有帮助。
关于node.js - 尚未为模型 "ResourceSchema"注册架构。 - 巢.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57431221/