我想将新文档添加到mongodb并获得插入的ID作为201状态的响应,但是当db.insertOne调用时,在水龙头工作之前我得到204状态代码的响应。这是我的控制器
@controller('/stars')
export class StarController {
constructor(@inject(TYPES.StarService) private starService: IStarService) {}
@httpPost('/')
public newStar(request: Request, response: Response) {
this.starService.insert(request.body)
.pipe(
tap(result => response.status(201).json(result))
).subscribe();
}
}
在我的StarService中
@injectable()
export class StarService implements IStarService {
private mongoClient: MongoDBClient;
constructor(@inject(TYPES.MongoDBClient) mongoClient: MongoDBClient) {
this.mongoClient = mongoClient;
}
public insert(star) {
return this.mongoClient.insertOne(star, 'stars');
}
在MongoDBClient中
public insertOne<T>(document: T, collectionName: string): Observable<ObjectID> {
return from(
this.db.collection(collectionName).insertOne(document))
.pipe(
map(
(result: InsertOneWriteOpResult) => {
return result.insertedId;
}));
}
如何获取具有正确状态代码和正文的json响应