0

I have an array with multiple values which need to be used as queries to search a collection. I am not sure of a way of doing this using one route. for example:

router.get('/', ensureAuthenticated, (req, res) => {
let ArrayOfIds = [id1, id2, id3]

Movie.find({user: req.user.id}).then(items => {
//Something along this lines 
 items.subscriptions.forEach(subscription => {
 Movie.find({user: subscription})
  //This wont work beacuse of the callback promise
   .then(movies => {
    items.push(movies)
 })
 })
res.render('index/home',
 {pageName: 'Movies', items: items})
 .catch(err => console.log(err));
});
})

I want to search the same collection (Movie) for each id and add it to the items object. Doing it with a for loop seems to create a set header error. Any ideas?

2 Answers2

0

This S/O response should have your answer...

Error: Can't set headers after they are sent to the client

From the response:

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.

In your case, you called res.redirect(), which caused the response to become Finished. Then your code threw an error (res.req is null). and since the error happened within your actual function(req, res, next) (not within a callback), Connect was able to catch it and then tried to send a 500 error page. But since the headers were already sent, Node.js's setHeader threw the error that you saw.

It's likely that you're calling res.redirect() multiple times if you're implementing a for-loop.

Will Ward
  • 1,886
  • 1
  • 10
  • 11
0

Maybe if I understand correctly, you can query the collection with list of ids in your case ArrayOfIds into in query of mongo. Check $in query of mongoDB. FYI: create some index on that field.