Hello I am having trouble implementing the last bit of code before I can (fingers crossed) launch my page. I implemented a "follow" feature (button) where a user can click to follow a story. All stories are displayed on the browse page but once followed, the stories display on the "library page". I got this to work however, I am having trouble with the "unfollow" portion to remove it from the library. Would ideally be the same button toggling between follow/unfollow, and so a conditional.
These are my routes:
// INDEX - show all stories
router.get("/browse", function(req, res){
// Get all stories from DB
Story.find({}, function(err, allStories){
if(err){
console.log(err)
} else {
res.render("stories/index", {stories:allStories})
}
})
})
// LIBRARY - show all stories in Library
router.get("/stories/:id/follow", middleware.isLoggedIn, function(req, res){
User.findById(req.user.id, function(err, foundUser){
if(err){
console.log(err)
} else{
foundUser.subscriptions.push(req.params.id);
foundUser.save();
res.redirect("/library")
}
});
});
router.get("/library", middleware.isLoggedIn, function(req, res){
User.findById(req.user.id).populate("subscriptions").exec(function(err, foundUser){
if(err){
console.log(err)
} else {
res.render("library", {subscriptions: foundUser.subscriptions});
}
});
});
Schemas:
var UserSchema = new mongoose.Schema({
username: String,
password: String,
subscriptions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Story"
}
]
})
var storySchema = new mongoose.Schema({ title: String, image: String, description: String, author: { id: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, username: String }, comments:[ { type: mongoose.Schema.Types.ObjectId, ref: "Comment" } ], content:[ { type: mongoose.Schema.Types.ObjectId, ref: "Content" } ]
})var storySchema = new mongoose.Schema({
title: String,
image: String,
description: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
comments:[
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
],
content:[
{
type: mongoose.Schema.Types.ObjectId,
ref: "Content"
}
]
})
Looking for something like ""if user subscriptions array already contains story id, then remove it, otherwise add it". Any help would be of tremendous value! Thank You.
via nguer092
No comments:
Post a Comment