2

I want to add new document to the mongodb and get an inserted id as response with 201 status, but when db.insertOne called I get response with 204 status code before tap works. Here is my controller

@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();
}
}

In my 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');
}

In 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;
                }));
}

How can I get json response with correct status code and body

Lilit
  • 21
  • 1
  • Hi Lilit. As I understood in your case when you call to insert it works but when you call insertOne it returns 204? – Armen Grigoryan Jul 19 '18 at 08:22
  • Hi Armen.Thank you for your response. No, after `this.db.collection(collectionName).insertOne(document)` I immediately get 204 response.And after that `map( (result: InsertOneWriteOpResult) => { return result.insertedId; })` works. – Lilit Jul 19 '18 at 08:30
  • And when `response.status(201).json(result)` called I am getting error "can't set headers after they are sent" – Lilit Jul 19 '18 at 08:31
  • it easy to catch, this error means that you already sent your http response header and it can't be changed or overridden. it associated with your http response and doesn't meter what you use mongodb or ms sql or mysql, I recomend you manualy set your http header and do not try change it like this response.addHeader("Content-Type", "application/json"); and so one ... – Armen Grigoryan Jul 19 '18 at 10:38
  • sorry response.addHeader is a java code on node js you can do res.set('Content-Type', 'application/json'); – Armen Grigoryan Jul 19 '18 at 10:46

0 Answers0