NestJS+MongoDB按Genre ID查询对应分类书籍及find非函数报错咨询
问题根源
- 运行时报错
this.book_model.find({}) is not a function:你在LibraryService构造函数中注入的book_model是BooksService类实例,不是Mongoose的Book模型实例,只有Mongoose模型才内置find等数据库操作方法,自定义的Service本身没有这个方法。 - 查询逻辑错误:你需要匹配Book集合中的
genres_id字段和传入的分类ID,原有查询条件不符合字段规则。
解决方案
方案1:直接在LibraryService中注入Book模型操作
首先修改library.service.ts:
- 导入Book相关类型:
import { Book, bookdocument } from './你的bookschema实际路径/bookschema';
- 修正构造函数的注入逻辑:
constructor( @InjectModel(Department.name) private readonly dep_model: Model<departmentdocument>, // 注入Book的Mongoose模型,替换原有注入的BooksService @InjectModel(Book.name) private readonly book_model: Model<bookdocument> ) { }
- 修正查询方法:
async getallBooksofSingleGenere(id: string) { // 匹配genres_id等于传入的分类ID return this.book_model.find({ genres_id: id }); }
- 补充Library模块的模型注册:
在library.module.ts的imports数组中添加Book模型注册:
MongooseModule.forFeature([ { name: Department.name, schema: departmentSchema }, { name: Book.name, schema: bookschema } ]),
方案2:复用现有BooksService(推荐,符合模块拆分原则)
- 在
books.service.ts中新增按分类ID查书的方法:
async getBooksByGenreId(genreId: string) { return this.bookModel.find({ genres_id: genreId }); }
- 修改
LibraryService的查询方法直接调用BooksService的新增接口即可:
async getallBooksofSingleGenere(id: string) { return this.book_model.getBooksByGenreId(id); }
优化建议
可以修正拼写错误,比如把getallBooksofSingleGenere改为getAllBooksOfSingleGenre,接口路径booksofperticulargenre改为books-of-particular-genre,更符合通用命名规范。
内容的提问来源于stack exchange,提问作者M Nouman
相关产品推荐
相关产品推荐

