I'm trying to make a mini social media API, and want to ensure that the each user can comment and like other posts but can't do that on their own post.
This is the code for my current like system, anyone has an idea of how do i revoke permission to like a post for that one specific user logged on?
// LIKE DISLIKE
router.put("/:id/like" ,verifyToken, async(req , res)=>{
try {
const post = await Post.findById(req.params.id);
if(!post.likes.includes(req.user._id)){
await post.updateOne({$push:{likes:req.user._id}})
return res.status(200).json("Post has been liked")
}else{
await post.updateOne({$pull:{likes:req.user._id}});
return res.status(200).json("Post has been unliked")
}
} catch (error) {
return res.status(500).json(err)
}
})
I've tried comparing the parameter of the user id (user:req.user._id) to the user ID of the one within the post but that didn't work.
post Schema
const mongoose = require('mongoose')
const postSchema = mongoose.Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
required:true
},
title:{
type:String,
required:true
},
description:{
type:String,
required:true
},
likes:{
type:Array,
deafult:0
},
date:{
type:Date,
default:Date.now
},
comments:[
{
user:{
type:mongoose.Schema.ObjectId,
required:true
},
profile:{
type:String
},
comment:{
type:String,
required:true
},
date: {
type: Date,
default:Date.now
}
}
]
})
module.exports=mongoose.model('post',postSchema)
CodePudding user response:
You could check if user
is equal to req.user._id
and block the operation in that case.
Also, you should change your likes
type declaration to an array of ObjectId
if you want to store user identifiers in there:
likes: [{
type: mongoose.Schema.Types.ObjectId,
deafult: []
}],
Try with this code:
router.put('/:id/like', verifyToken, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.user === req.user._id) {
return res.status(400).json({ message: 'You cannot like your own posts.' })
}
if (!post.likes.includes(req.user._id)) {
post.likes.push(req.user._id);
await post.save();
return res.status(200).json({ message: 'Post has been liked' });
} else {
post.likes = [...post.likes].filter(id => id !== req.user._id);
await post.save();
return res.status(200).json({ message: 'Post has been unliked' });
}
} catch (error) {
return res.status(500).json(err);
}
});