Saturday, 13 May 2017

Node.js removing element from associated element

I added a feature where users can pin recipes to their profile. However, when the recipe is deleted, the recipe isn't removed from the user's pinnedRecipes, even though it doesn't appear on the user's show page (the ID stays in the user's pinnedRecipes in the database).

Here's the association between the Recipes and the user's pinnedRecipes:

var userSchema = new mongoose.Schema({
    username: String,
    password: String,
    admin: {type:Boolean, default: false},
    bio: {type:String, default: "Cet utilisateur n'a pas encore rempli cette section."},
    profileImage: {type:String, default: "http://www.wilwia.com/images/default-user.png"},
    pinnedRecipes:[
        {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Recipe"
        }
    ]
});

var recipeSchema = new mongoose.Schema({
    title: String,
    source: String,
    image: String,
    preplength: String,
    cooklength: String,
    portions: Number,
    description: String,
    ingredients: String,
    instructions: String,
    createdAt: { type: Date, default: Date.now },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String,
    },
    comments: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Comment"
            }
        ],
    category: {type:String, enum: ['appetizer', 'salad', 'soup', 'meat', 'pasta', 'breakfast', 'dessert']}
});

Here's what I tried, that didn't work (everything works, except removing recipe from pinnedRecipes):

    //DESTROY ROUTE
router.delete("/:id", middleware.checkRecipeOwnership, function(req, res){
    Recipe.findById(req.params.id, function(err, foundRecipe){
        if(err){
            res.redirect("back");
        } else {
            //delete associated comments
            if(foundRecipe.comments.length > 0){
                Comment.remove({
                _id: {
                    $in: foundRecipe.comments
                }
            }, function(err){
                if(err){
                    console.log(err);
                }
            });
            //delete from every user's pinned recipes
            User.find({pinnedRecipes: "ObjectId(" + foundRecipe._id + ")"}, function(err, foundUsers){
                if(err){
                    console.log(err);
                } else {
                    console.log(foundUsers);
                    foundUsers.forEach(function(user){
                        user.pinnedRecipes.remove(foundRecipe);
                        user.save();
                    });
                }
            });
            //remove the campground
            foundRecipe.remove(function(err, recipe){
               if(err){
                   console.log(err);
                   res.redirect("/recipes");
               } else {
                   res.redirect("/recipes");
               }
            });
            }
        }
    });
});

Also, here's how recipes are pinned:

// PIN ROUTE
router.get("/pin/:id", middleware.isLoggedIn, function(req, res){
    Recipe.findById(req.params.id, function(err, foundRecipe){
        if(err){
            req.flash("error", "Une erreur s'est produite.");
            res.redirect("/recipes/" + foundRecipe._id);
        } else {
            User.findById(req.user._id, function(err, user){
                if(err){
                    req.flash("error", "Une erreur s'est produite.");
                    res.redirect("/recipes/" + foundRecipe._id);
                } else { 
                  user.pinnedRecipes.push(foundRecipe);
                  user.save();
                  res.redirect("/recipes/" + foundRecipe._id);
                  req.flash("success", "Pinned recipe"); 
                }
            });
        }
    });
});

// UNPIN ROUTE
router.delete("/pin/:id", middleware.isLoggedIn, function(req, res){
    Recipe.findById(req.params.id, function(err, foundRecipe){
        if(err){
            req.flash("error", "Une erreur s'est produite.");
            res.redirect("/recipes/" + foundRecipe._id);
        } else {
            User.findById(req.user._id, function(err, user){
                if(err){
                    req.flash("error", "Une erreur s'est produite.");
                    res.redirect("/recipes/" + foundRecipe._id);
                } else { 
                  user.pinnedRecipes.remove(foundRecipe);
                  user.save();
                  res.redirect("/recipes/" + foundRecipe._id);
                  req.flash("success", "Pinned recipe"); 
                }
            });
        }
    });
});

Thanks a lot!



via Davycodes

No comments:

Post a Comment