0

I am a beginner, and I am doing basic backend that runs on node.js and has express.js and mongodb. My db model has one model - Story:

var storySchema = new mongoose.Schema({
  name: String
});
var model = mongoose.model('Story', storySchema);

on get request I am trying take the data from db to display it, so I have:

 var stories = [
 'randomString',
 'randomString',
 'randomString'
];

stories.forEach(function(story, index) {
  Story.find({'name': story}, function(err, stories) {
    if(!err && stories.length) {
      Story.create({name: story});
    };
  });
});

However in my stories.forEach something went wrong, so I got the error "can't set headers after they are sent".

Can you please help me out?

Based on comments, in my index.js I got:

router.get('/stories', function(req, res) {
  Story.find({}, function(err, stories) {
    if(err) {
      return res.status(500).json({message: err.message});
    } res.json({stories: stories});
  })
  res.json({stories:[]});
   });                                   
Brinka
  • 89
  • 7
  • 2
    The error you have seems related to `http` or `express`, not `mongoose`, are you sure the error come from this part of your code? – DrakaSAN Aug 18 '16 at 14:41
  • 1
    hum don't you have a `res.send` in you forEach ? – Olivier Boissé Aug 18 '16 at 14:41
  • Seems you are trying to return more than one response to the client – Sanandrea Aug 18 '16 at 14:41
  • updated the question – Brinka Aug 18 '16 at 14:45
  • To elaborate, the error comes from your application trying to render headers on the page more than once. `res.json()` or `res.send()` write headers to the output; if `Story.create()` for example sends headers or tries to manipulate them, that may very well be causing the problem. – brandonscript Aug 18 '16 at 14:47
  • Dumb mistake, thanks everyone! Thanks @brandonscript – Brinka Aug 18 '16 at 14:50
  • 1
    Possible duplicate of [Node.js Error: Can't set headers after they are sent](http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent) – Ben Fortune Aug 18 '16 at 14:53

0 Answers0