You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS+MongoDB按Genre ID查询对应分类书籍及find非函数报错咨询

问题根源

  1. 运行时报错this.book_model.find({}) is not a function:你在LibraryService构造函数中注入的book_model是BooksService类实例,不是Mongoose的Book模型实例,只有Mongoose模型才内置find等数据库操作方法,自定义的Service本身没有这个方法。
  2. 查询逻辑错误:你需要匹配Book集合中的genres_id字段和传入的分类ID,原有查询条件不符合字段规则。

解决方案

方案1:直接在LibraryService中注入Book模型操作

首先修改library.service.ts:

  1. 导入Book相关类型:
import { Book, bookdocument } from './你的bookschema实际路径/bookschema';
  1. 修正构造函数的注入逻辑:
constructor(
  @InjectModel(Department.name) private readonly dep_model: Model<departmentdocument>,
  // 注入Book的Mongoose模型,替换原有注入的BooksService
  @InjectModel(Book.name) private readonly book_model: Model<bookdocument>
) { }
  1. 修正查询方法:
async getallBooksofSingleGenere(id: string) {
  // 匹配genres_id等于传入的分类ID
  return this.book_model.find({ genres_id: id });
}
  1. 补充Library模块的模型注册:
    在library.module.ts的imports数组中添加Book模型注册:
MongooseModule.forFeature([
  { name: Department.name, schema: departmentSchema },
  { name: Book.name, schema: bookschema }
]),

方案2:复用现有BooksService(推荐,符合模块拆分原则)

  1. 在books.service.ts中新增按分类ID查书的方法:
async getBooksByGenreId(genreId: string) {
  return this.bookModel.find({ genres_id: genreId });
}
  1. 修改LibraryService的查询方法直接调用BooksService的新增接口即可:
async getallBooksofSingleGenere(id: string) {
  return this.book_model.getBooksByGenreId(id);
}

优化建议

可以修正拼写错误,比如把getallBooksofSingleGenere改为getAllBooksOfSingleGenre,接口路径booksofperticulargenre改为books-of-particular-genre,更符合通用命名规范。

内容的提问来源于stack exchange,提问作者M Nouman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:45:01