I am a beginner and i want to create follow/unfollow functionality in my app.
router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{
user.findById(req.params.id)
.then((otherUser)=>{
if(otherUser.followers.includes(req.userInfo._id)){
return res.json({message: "Already following user"});
}
req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});
res.json({message: "following user"});
console.log(otherUser.followers);
})
.catch((e)=>{
res.json(e);
})})
when running the code it recieves the message "following user" but dosen't add to the database i.e. Mongodb (i'm using MERN stack)
It seems like this block of code is not executing.
req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});
what am i doing wrong here?
CodePudding user response:
I think that is because req.userInfo and otherUser is an immutable mongo object. try this instead (assuming "user" is your model object):
user.updateOne(
{ _id: req.userInfo._id},
{$push: {followings: req.params.id}
)
user.updateOne(
{ _id: otherUser._id},
{ $push: {followers: req.userInfo._id}}
)
note: while comparing _id please check if you are storing as objectId or string.
for your reference: Comparing mongoose _id and strings
CodePudding user response:
Well, this seems to work
router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{
user.findById(req.params.id)
.then((otherUser)=>{
if(!otherUser.followers.includes(req.userInfo._id)){
Promise.all([
user.updateOne({_id:req.userInfo._id}, {$push: {followings: req.params.id}}),
user.updateOne({_id: otherUser._id},{$push: {followers: req.userInfo._id}})
]).then(()=>{
res.json({message: "following user"});
})
.catch((e)=>{
res.json(e);
});
}else{
return res.json({message: "Already following user"});
}
})
});
But it would be better if someone explained what went wrong previously, as I said i am beginner and would appreciate the feedback.