favoritesRouter.route('/:dishId') .delete(Verify.verifyOrdinaryUser, function(req, res, next) { var userID = req.decoded._doc._id; Favorites.find({"forUser": userID}) .populate('forUser favoriteDishes') .exec(function(err, result) { if (err) throw err; if (result.length !== 0 && result[0].favoriteDishes.length !== 0) { // Does the user have favorite dishes? var dishId = req.params.dishId, deleted = false; for (var i = 0; i < result[0].favoriteDishes.length; i++) { if (result[0].favoriteDishes[i]._id == dishId) { result[0].favoriteDishes.splice(i, 1); result[0].save(function(err, result) { if (err) throw err; }); deleted = true; } } res.json(deleted ? {status: "deleted dish [" + dishId +"] from favorites"} : {status: "user did not have dish [" + dishId + "] as a favorite"} ); }; }); });
Favorites.create({forUser: userID}, function (err, favorite) { if (err) throw err; favorite.favoriteDishes.push(favDishID); favorite.save( function (err, favorites) { if (err) throw err; for (var i = 0; i < result[0].favoriteDishes.length; i++) { if (result[0].favoriteDishes[i]._id == favDishID) duplicate = true; // ...yes! result[0].favoriteDishes.push(favDishID); result[0].save( function(err, favorites) { if (err) throw err;