nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解释,运行起来了,不会操作

来源:互联网  时间:2018/1/27 1:40:24

关于网友提出的“ nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解释,运行起来了,不会操作”问题疑问,本网通过在网上对“ nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解释,运行起来了,不会操作”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解释,运行起来了,不会操作
描述:

1.我现在就想用nestjs在mongodb上建库和查询,官方例子不会操作

就这样的
cats.controller.ts里的

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  @Get()
  async findAll(): Promise {
    return this.catsService.findAll();
  }
}

cats.service.ts里的

@Component()
export class CatsService {
  constructor(
    @Inject('CatModelToken') private readonly catModel: Model) {}

  async create(createCatDto: CreateCatDto): Promise {
    const createdCat = new this.catModel(createCatDto);
    return await createdCat.save();
  }

  async findAll(): Promise {
    return await this.catModel.find().exec();
  }
}

把服务启动后访问localhost:3000之后怎么操作


解决方案1:

被@Post()修饰的 create方法 是用来创建数据的 , 具体步骤:

{

 "name": "name1",
 "age":  1,
 "breed": "breed1"

}
  1. 这个数据放在请求的body里 , 它的格式是json的
  2. 用post请求方式访问URL:http://localhost:3000/cats , 要带上数据

我刚刚成功了 , 用的工具是 postman.

被@Get()修饰的 findAll方法类似.

解决方案2:

@POST()
async create(@Body() createCatDto: CreateCatDto,@Response() res) {
    let catPromise = this.catsService.create(createCatDto);
    catPromise
    .then( cat=>{
      res.status(HttpStatus.OK).json(cat);//返回新创建的doc
    })
    .catch( err=>{
      res.status(HttpStatus.OK).json(err);//返回错误
    });
  }

前端发送请求,使用angularjs

上一篇mongodb如何获得集合中所有最后更新的一批数据?
下一篇mongodb添加了2000多条数据就无法继续添加了
明星图片
相关文章
《 nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解释,运行起来了,不会操作》由码蚁之家搜集整理于网络,
联系邮箱:mxgf168#qq.com(#改为@)