Nestjs中的MissingSchemaError
Posted
技术标签:
【中文标题】Nestjs中的MissingSchemaError【英文标题】:MissingSchemaError in Nestjs 【发布时间】:2022-01-10 09:21:21 【问题描述】:大家好,我无法指定与另一个模型的关系。当我添加一个关系时,它向我显示了这个错误
图书模型
import Prop, Schema, SchemaFactory from '@nestjs/mongoose';
import Document from 'mongoose';
export type BookDocument = Book & Document;
@Schema( timestamps: true, collection: 'books' )
export class Book
@Prop( type: String, required: true )
name: string;
@Prop( type: String, required: true )
author: string;
@Prop( type: String, required: true )
bookType: string;
export const BooksSchema = SchemaFactory.createForClass(Book);
图书借阅模式
import Prop, Schema, SchemaFactory from '@nestjs/mongoose';
import Schema as mongooseSchema, Document from 'mongoose';
import Book from '../../books/enitiy/book.model';
import IsNotEmpty from 'class-validator';
export type BookLendDocument = BookLend & Document;
@Schema( timestamps: true )
export class BookLend
@IsNotEmpty()
@Prop( type: mongooseSchema.Types.ObjectId, ref: 'books', required: true )
bookId: Book;
@IsNotEmpty()
@Prop( type: String, required: true )
name: string;
@IsNotEmpty()
@Prop( type: String, required: true )
returnDate: string;
@Prop( type: String )
returnedOn: string;
@IsNotEmpty()
@Prop( type: String, required: true )
status: string;
export const BookLendSchema = SchemaFactory.createForClass(BookLend);
我将书籍 objectID 引用到 booklend booksID ,当我使用下面的代码时,我收到错误 MissingSchemaError: Schema hasn't been registered for model "books".
const allBookLendDetails = await this.bookLend
.find()
.populate('bookId')
.exec();
【问题讨论】:
【参考方案1】:嗨,我通过将BooksSchema
导入BookLend
模块文件来修复它
这里参考代码:-
import Module from '@nestjs/common';
import BookLendService from './book-lend.service';
import BookLendController from './book-lend.controller';
import MongooseModule from '@nestjs/mongoose';
import BookLendSchema from './entities/book-lend.entity';
import CommonService from '../common-service/common-service.service';
import BooksSchema from '../books/enitiy/book.model';
@Module(
imports: [
MongooseModule.forFeature([
name: 'booklend', schema: BookLendSchema ,
name: 'books', schema: BooksSchema ,
]),
],
controllers: [BookLendController],
providers: [BookLendService, CommonService],
)
export class BookLendModule
在服务文件中,需要注入模型
constructor(
@InjectModel('booklend') private readonly bookLend: Model<BookLend>,
@InjectModel('books') private readonly books: Model<Book>
)
【讨论】:
以上是关于Nestjs中的MissingSchemaError的主要内容,如果未能解决你的问题,请参考以下文章
NestJS/Mongoose:序列化不排除普通输出中的属性