【问题标题】:Fetch all the books of a particular Genre获取特定类型的所有书籍
【发布时间】:2021-12-18 03:51:08
【问题描述】:

*我在 nestJs 中使用 mongodb 编写代码。场景是我有 2 个模块 用于流派和书籍。在 mongodb 中,Genres 和 Books 都存储不同的模式。我有一个 @Get 方法,它接受一个流派的 id 并返回存储在数据库中的所有书籍。但我想要的是,该函数将采用流派的 id,并应返回有关该流派的书籍。例如,如果我给出英语流派的 id,那么该函数应该只返回英语书籍。并不是数据库中的所有书籍。 请阅读所有声明和代码。 而且这个问题的标题可能不对,你可以建议。

我希望您能理解我要问的问题。如果您需要有关代码或其他任何内容的更多详细信息,我会提供。

现在我正在尝试的逻辑是使用代码

bookschema.ts。书籍的架构。这里的 'genres_id' 是特定流派 id 的 id,人们在发布(@Post)一本书以及其他书籍属性时会给出它。

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
@Schema()
export class Book {
    @Prop()
    name: string
    @Prop()
    author: string
    @Prop()
    price: number
    @Prop()
    genres_id: string

}


export const bookschema = SchemaFactory.createForClass(Book)
export type bookdocument = Book & Document

library.service.ts(library.service for 'genres'),在这个文件中我试图实现,getallBooksofSingleGenere(id: any), function 来获取特定类型的书籍,我想写一个像“find({id:genre_id})”这样的逻辑。但是我的这个逻辑是不对的。我想要这个函数中的逻辑,它将返回特定类型的书籍。

2-而且我在运行时遇到错误,而不是在编译时,说 “this.book_model.find({})” 不是函数。我不知道为什么会出现错误。

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { BooksService } from './books/books.service';
import { Department, departmentdocument } from './departments-schema';


@Injectable()
export class LibraryService {
    constructor(@InjectModel(Department.name) private readonly dep_model: Model<departmentdocument>,private readonly book_model: BooksService) { }

    async getalldepartments() {
        return this.dep_model.find();
    }
    async getdepartmentbyid(depID){
        return this.dep_model.findById(depID)
    }
    async getallBooksofSingleGenere(id:any)
    {
       //return this.book_model.find(id)
       //return this.book_model.find({books:id})
       //return this.book_model.getallbooks() //this logic returns all the books present in database
       return this.book_model.find({});//I want to run this logic somehow.

    }
    async adddepartment(department) {
        const newdepartment = new this.dep_model(department)
        return newdepartment.save()
    }
    async putupdatedepartment(id: string, department: departmentdocument) {
        return await this.dep_model.findByIdAndUpdate(id, department)
    }
    async patchupdatedepartment(id: string, department: departmentdocument) {
        return await this.dep_model.findByIdAndUpdate(id, department)
    }
    async deletedepartment(id: string) {
        return await this.dep_model.findByIdAndDelete(id)
    }

}

library.controller.ts(类型控制器)。这里的第二个@Get,采用流派 id 并获取 id 流派的文档。 第三个@Get,检查 id 是否属于流派。第三个@Get,检查它确保id必须是流派的id。

import { Body, Controller, Delete, Get, HttpException, Param, Patch, Post, Put } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { departmentdocument } from './departments-schema';
import { LibraryService } from './library.service';

@ApiTags('Genre')
@Controller('Genres')
export class LibraryController {
    constructor(private lib_service: LibraryService) { }

    @Get()
    async getalldepartments() {
        return this.lib_service.getalldepartments()
    }
    @Get('genres/:depid')
    async getdepartmentbyid(@Param('depid') depid: string) {
        return this.lib_service.getdepartmentbyid(depid)
    }
    @Get('booksofperticulargenre/:id')
    async getallBooksofSingleGenere(@Param('id') id: string) {
        var check = await this.lib_service.getdepartmentbyid(id);
        if (check != null) { return this.lib_service.getallBooksofSingleGenere(id) }
        else {

            throw new HttpException('ID does not match to any Genres,Please Enter a valid Genre ID', 404)
        }

    }
    @Post()
    async adddepartments(
        @Body() department: string,) {
        const adddepartment = await this.lib_service.adddepartment(department)
        return adddepartment
    }
    @Put(':id')
    async putupdatedepartment(@Param('id') id: string, @Body() department: departmentdocument) {
        const updatedepartments = await this.lib_service.putupdatedepartment(id, department)
        return updatedepartments
    }
    @Patch(':id')
    async patchupdatedepartment(@Param('id') id: string, @Body() department: departmentdocument) {
        return await this.lib_service.patchupdatedepartment(id, department)

    }
    @Delete(':id')
    async deletedepartment(@Param('id') id: string) {
        await this.lib_service.deletedepartment(id);
    }
}

WC-LIBRARY(DATABASE) 还有两个模式

【问题讨论】:

    标签: mongodb mongoose mongodb-query nestjs


    【解决方案1】:

    应该在 Mongoose 模型上触​​发那些数据库查询调用(查找、更新..)。虽然名字是 book_model,但我不认为它实际上是一个书籍模型,因为它的类型是 BooksService。 Book 模型应该和你注入 dept 模型的方式一样。

    genre_id 是自动生成的标识符 - 还是 - 它指向其他集合 (ObjectId)?

    【讨论】:

    • 是的,genre_id 是添加流派时 mongodb 生成的 id。第二,我错过了我使用服务而不是 bookdocument 的观点。第三件事是我已经为我的 sceario 制定了解决方案。
    【解决方案2】:

    为了获得所需的场景解决方案,我进行了三处更改。

    1.如果要使用mongodbfind()等函数等,library.sevice.ts中的Constructor应该是这样的

        @Injectable()
        export class LibraryService {
            constructor(@InjectModel(Department.name) 
         private readonly dep_model: Model<departmentdocument>,
    @InjectModel(Book.name)private readonly book_model: Model<bookdocument>) { }
    

    2.您还必须添加我之前缺少的以下代码。就像每当您需要在服务中使用其他模块(用于数据库目的的整个模块)时,您必须引入该模块和模块的架构在第二个模块的导入中(如果我只有 2 个模块,所以在你的情况下,你必须弄清楚你想在其他模块中导入哪个模块)。否则你会得到一个错误,比如“确保索引处的模块应该在 x_module' 中

    @Module({
          imports: [BooksModule,
          MongooseModule.forFeature([{
            name: Department.name,
            schema: departmentschema
          }]),
          MongooseModule.forFeature([{
            name: Book.name,
            schema: bookschema
          }]),
        ],
    

    3.获取特定类型书籍的功能如下所示。如果遇到某种错误,您可以将id更改为字符串类型。要了解数据库查询的工作原理,您可以访问链接(我建议您简要彻底地阅读文档)https://docs.mongodb.com/manual/reference/method/db.collection.find/

      async getallBooksofSingleGenere(id:any)
        {
    
           return this.book_model.find({genres_id:id})
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多