ค้นหาเว็บไซต์

typescript - ได้รับการตอบกลับ 204 ก่อนการเรียก callback ของฐานข้อมูลใน expressjs, mongodb, inversifyjs


ฉันต้องการเพิ่มเอกสารใหม่ลงใน MongoDB และรับ ID ที่ถูกแทรกเป็นการตอบกลับพร้อมกับสถานะ 201 แต่เมื่อเรียกใช้ db.insertOne ฉันได้รับการตอบกลับด้วยรหัสสถานะ 204 ก่อนที่ tap จะทำงาน นี่คือคอนโทรลเลอร์ของฉัน

@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 พร้อมรหัสสถานะและเนื้อหาที่ถูกต้องได้อย่างไร