0

I am trying to update two seperate collections in a mongoDB database using mongoose and node.js. But I am getting an error for setting headers after they are sent. This is the error

The code that is being used to set this up is : Code

Line 170 is the line where customer.update is written

1 Answer 1

3

You trying to send response two times after customer and admin collection update. That's why you got this error.

To solve this. Use async library http://caolan.github.io/async/docs.html#.parallel

Or custom functions with callbacks and only send headers when all collections got updated.

here is example

async.parallel([
   adminName: function(callback) {
      admin.update({yourUpdateCode}, function(err, AdminDoc){
         //you may want to add error handling here
         callback(null, AdminDoc);
      });
   },
   customerName: function(callback) {
      customer.update({yourUpdateCode}, function(err,doc){
       //you may want to add error handling here
        callback(null, CustDoc);
      });
   }],
function(err, results) {
   // results is now equals to: {adminName: AdminDoc, customerName: CustDoc}
   //your final callback here.
});

Hope this helps.

Sign up to request clarification or add additional context in comments.

10 Comments

Do we need to install some specific npm package for this?
Well..You can use async lib as give you reference to DOCS. You can use promises if you want. You also can create methods that will update each collection and return final result to main function. About ASYNC. Yes you need to install it using npm.
ok. What is the collName referring to in your inital snippet?
Async each iterates over array of values and pass each value to callback function..Let me change example. So you understand better
Ya that will be great
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.