Skip to content

Instantly share code, notes, and snippets.

@tsongas
Created February 10, 2017 06:00
Show Gist options
  • Save tsongas/4ec55db2f93f848b67582e09713ee7c6 to your computer and use it in GitHub Desktop.
Save tsongas/4ec55db2f93f848b67582e09713ee7c6 to your computer and use it in GitHub Desktop.
You don't have to immediately chain a promise, so just use the if/else to set a promise variable, and then set up a chain on that.
Setlist.count({}, (err, count) => {
let promise;
// if db is empty, create a setlist
if (count === 0) {
promise = Setlist.create({
tracks: [req.body.track]
});
} else {
// add track to setlist
promise = Setlist.findOneAndUpdate({},
{$push: {tracks: req.body.track}},
{new: true}
);
}
promise.then(setlist => {
res.status(201).json(setlist);
}).catch(err => {
console.error(err);
res.status(500).json({message: 'Internal server error'});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment