按类别获得所有记录NestJs + MongoDB + Mongoose

问题描述 投票:0回答:1

我正在使用NestJs + MongoDB + Mongoose,我想获取MongoDB中的所有记录以及按参数发送的记录,但我没有,我是一个初学者。如何获得同一类别的所有记录?我在请求中发送了类别ID,但是我没有收到该类别的所有记录,您能帮我吗?

我需要这个:

获取/用户/食物并返回此:

{“密码”:“ 123”,“ name”:“ Brian”,“ adress”:“”,“电子邮件”:“ a @ a”,“类别”:“食物”,“ cpfOrCnpj”:“字符串”},

{“密码”:“ 123”,“ name”:“ Margo”,“ adress”:“”,“电子邮件”:“ a @ a”,“类别”:“食物”,“ cpfOrCnpj”:“字符串”}

我的代码:

我的服务:

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User } from './user.model';
import { Model } from 'mongoose';

@Injectable()
export class UserService {
  constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

  async create(doc: User) {
    //Ok
    const result = await new this.userModel(doc).save();
    return result.id;
  }

  async find(id: string) {
    return await this.userModel.findById(id).exec();
  }


  async update(user: User) {
    //Test
    return await this.userModel.findByIdAndUpdate(user);
  }

}

我的控制器:

import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.model';

@Controller('user')
export class UserController {
  constructor(private service: UserService) {}

  @Get(':id')
    async find(@Param('category') id: string) {
    return this.service.find(id);
  }

  @Post('create')
  create(@Body() user: User) {
    return this.service.create(user);
  }

  @Put('update')
  update(@Body() user: User) {
    return this.service.update(user);
  }

}
node.js mongodb mongoose nest nestjs
1个回答
0
投票

在此功能中

  find(id: string) {
    return this.userModel.findById(id).exec();
  }

您正在按_id搜索,findById方法用于按文档的_id进行过滤

我认为category不是您文档的_id

因此,您需要使用常规的find方法,并将对象传递给它

  find(id: string) { // id is not _id here, I suggest you to name it category instead 
    return this.userModel.find({ category: id }).exec();
  }

注意,您在这里不需要异步/等待,因为您将返回承诺本身

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.