鍍金池/ 問答/數(shù)據(jù)庫  HTML/ nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解釋

nestjs 使用mongoose操作mongodb ,官方例子看不懂,求解釋,運(yùn)行起來了,不會操作

1.我現(xiàn)在就想用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<Cat[]> {
    return this.catsService.findAll();
  }
}

cats.service.ts里的

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

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

  async findAll(): Promise<Cat[]> {
    return await this.catModel.find().exec();
  }
}

把服務(wù)啟動后訪問localhost:3000之后怎么操作

回答
編輯回答
孤毒

被@Post()修飾的 create方法 是用來創(chuàng)建數(shù)據(jù)的 , 具體步驟:

{
 
 "name": "name1",
 "age":  1,
 "breed": "breed1"
 
}
  1. 這個數(shù)據(jù)放在請求的body里 , 它的格式是json的
  2. 用post請求方式訪問URL:http://localhost:3000/cats , 要帶上數(shù)據(jù)

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

被@Get()修飾的 findAll方法類似.

2018年6月15日 01:52
編輯回答
安于心
@POST()
async create(@Body() createCatDto: CreateCatDto,@Response() res) {
    let catPromise = this.catsService.create(createCatDto);
    catPromise
    .then( cat=>{
      res.status(HttpStatus.OK).json(cat);//返回新創(chuàng)建的doc
    })
    .catch( err=>{
      res.status(HttpStatus.OK).json(err);//返回錯誤
    });
  }

前端發(fā)送請求,使用angularjs

cat ={name:'tom',age:1,breed:'i'm tom cat'};
$http({method:'POST', data: cat, url: nbConfig.api + '/cats'})
            .success(function(data,status,headers,config){
                if(data.ResStatus=='success'){
                    HulaNotifyService.alert('提示',data.resMsg,'關(guān)閉');
                }else{
                    HulaNotifyService.alert('提示',data.resMsg,'關(guān)閉');
                }
                
            })
2018年3月19日 17:43