I am attempting to add a following/followers feature for a nodejs/mongoose driven website. I am having issues with getting the ID's stored properly using the methods below. Not quite sure what is going wrong but it appears to be saving only the ID properly to the following portion but not updating the followers for the first portion.
I know it would be easy if the user ID is just passed to the post request, but I thought storing the user ID on the front-end is kind of a security issue so just using the username to get the ID would be better.
// Handles the post request for following a user
router.post('/follow-user', function(req, res, next) {
// First, find the user from the user page being viewed
User.findOne({ username: req.body.username }, function(err, user) {
// Add to users followers with ID of the logged in user
user.followers = req.user._id;
// Create variable for user from page being viewed
var followedUser = user._id;
// Save followers data to user
user.save();
// Secondly, find the user account for the logged in user
User.findOne({ username: req.user.username }, function(err, user) {
// Add the user ID from the users profile the follow button was clicked
user.following = followedUser;
// Save following data to user
user.save();
});
});
});
The user model looks as such
var userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, required: true },
avatar: { type: String },
bio: { type: String },
following: [{ type: Schema.ObjectId, ref: 'User' }],
followers: [{ type: Schema.ObjectId, ref: 'User' }],
});
Any insight on this would be greatly appreciated.
via user3630457
No comments:
Post a Comment