Rafael Miller Rafael Miller - 1 year ago 119
Node.js Question

mongodb update is throwing a critical error

When I try to update a user using a web form, it runs a app.post on express. The object user is correct, but sometimes it throws a error in node console

app.post('/register/update', jsonParser, (request, response) => {
let user = request.body.user;
let users = mongoUtil.users();


users.update({email: user.email}, user, (err, res) => {
if(err) {

In node console:

{ _id: '578246ec9eb0587a5d67b8c9',
email: 'test@test.com',
zipcode: '1231-123',
companyName: 'test',
tradeName: 'test',
contactName: 'Test',
tel: '(14) 1232-1231',
password: 'test',
passwordConfirm: 'test',
adress: 'test',
adressComplement: 'test',
adressNumber: '123' }
/home/ec2-user/ ... /mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
at ServerResponse.header (/home/ec2-user/ ... /node_modules/express/lib/response.js:719:10)
at ServerResponse.contentType (/home/ec2-user/ ... /node_modules/express/lib/response.js:552:15)
at ServerResponse.sendStatus (/home/ec2-user/ .. /node_modules/express/lib/response.js:340:8)
at users.update (/home/ec2-user/menuWebApp/server/app.js:94:14)
at handleCallback (/home/ec2-user/ ... /node_modules/mongodb/lib/utils.js:96:12)
at /home/ec2-user/ ... /node_modules/mongodb/lib/collection.js:1008:42
at commandCallback (/home/ec2-user/ ... /node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1194:9)
at Callbacks.emit (/home/ec2-user/ ... /node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
at Connection.messageHandler (/home/ec2-user/ ... /node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:358:23)

I'm probably dealing with a callback problem, but I don't have idea how to solve it D:

Answer Source

The error is not coming from the update statement itself its coming from your callback function.

Specifically these lines of code.

if(err) {

What you are doing is if there is an error send the status 400, then send the status 201. The problem is once you send a response with your headers to the requestor you can't try and set the headers again.

So your code should change to:

if(err) {

So if an error is generated you will send a 400 response otherwise you will send a 201 response instead of trying to send a 400 response and then a 201 response immediately after.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download