node.js - 按类别获取所有记录 NestJs + MongoDB + Mongoose
问题描述
我正在使用 NestJs + MongoDB + Mongoose,我想用我通过参数发送的记录来获取 MongoDB 中的所有记录,但我没有得到它,我是初学者。如何获取同一类别的所有记录?我在请求中发送了类别 ID,但我没有收到该类别的所有记录,您能帮帮我吗?
我需要这个:
获取 /users/food 并返回:
{ “密码”:“123”,“姓名”:“布莱恩”,“地址”:“”,“电子邮件”:“a@a”,“类别”:“食物”,“cpfOrCnpj”:“字符串”} ,
{ “密码”:“123”,“姓名”:“Margo”,“地址”:“”,“电子邮件”:“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);
}
}
解决方案
在这个函数中
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();
}
请注意,这里不需要 async/await,因为您正在返回 Promise 本身
希望能帮助到你
推荐阅读
- python - 当行数不同时,Pandas 条件总和行进入新列
- java - android中不同数据包的BLE广告
- laravel - 使用 Phpunit/ 为什么 phpunit 会删除我数据库中的所有数据
- android - 安装 react-native-device-info 错误 android 后
- java - 在 Maven 构建的 EAR 中绑定文件
- perl - 无法安装 SOAP LITE
- laravel - laravel 集合形式的默认行数
- ios - Info.plist 文件中缺少目的字符串 - Xcode 10.1 和 iOS 10.0
- ros - 无法使用 urdf2webbots 工具从 urdf 转换 Kinova Arm
- haskell - 生成满足 QuickCheck 中特定属性的数据的最佳做法是什么?