简体   繁体   中英

Get all records by category NestJs + MongoDB + Mongoose

I'm using NestJs + MongoDB + Mongoose, and I would like to get all the records in MongoDB with the record that I send by parameter, but I'm not getting it, I'm a beginner. How could I get all records from the same category? I send the category ID in the request, but I don't receive all the records for that category, could you help me?

I need this:

GET /users/food and return this:

{ "password": "123", "name": "Brian", "adress": "", "email": "a@a", "category": "food", "cpfOrCnpj": "string" },

{ "password": "123", "name": "Margo", "adress": "", "email": "a@a", "category": "food", "cpfOrCnpj": "string" }

my code:

my service:

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);
  }

}

my controller:

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);
  }

}

In this function

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

you're searching by the _id , findById method is used to filter by the _id of the document

I think category is not the _id of your document here

so, you need to use the normal find method, and pass an object to it

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

Note, you don't need the async/await here, as you are returning the promise itself

hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM