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:[]});
});