Search code examples
node.jsmern

If block is not executing even after condition is satisfied in node.js


exports.deletePost = (req, res) => {
 const post = req.post;
 let postId = req.post._id;
 let userType = req.post.userType;
 let userId = _.trim(req.post.user._id, 'new ObjectId(")');

 post.remove((err, post) => {
      if(err)
           return res.status(400).json({error:"Failed to delete the post"});
      //res.json({message:"Post deleted successfully"});
      console.log("post deleted!");
 });

 if (userType=="User") {
      User.findById(userId).exec((err, user) => {
           if(err)
                return res.status(400).json({error:err})
           else if(!user)
                return res.status(400).json({error:"User not found!"})
           else {
                let removeIndex = 0;
                user.posts.map((post, index) => {
                     console.log(post+"======="+postId); //its matching for specified postId but if block it not executed
                     if (post === postId) {
                          console.log("found the post!!!!!!!!!!!!");//never executing this block even if condition is true
                          removeIndex = index;
                     }
                })
                console.log(removeIndex); //its always 0
                user.posts.splice(removeIndex, 1);
                console.log(user.posts); //so its removing first post everytime

                User.findByIdAndUpdate(
                     {_id: userId},
                     {$set: {posts: user.posts}},
                     {new: true},
                     (err, nuser) => {
                          if(err)
                               return res.status(400).json({error:"Failed to remove post from user's database!"});
                          nuser.salt = undefined;
                          nuser.encry_password = undefined;
                          nuser.createdAt = undefined;
                          nuser.updatedAt = undefined;
                          res.json(nuser);
                })
           }
      });

 }

in this code im fetching users post and want to remove the specific post's id from the array. i used map function to loop through all postIds and checking everytime if its the specified one by if statement. even if the condition is true, the block not executing (its not setting removeIndex = index)


Solution

  • I converted postId to string and it worked. It should be by default string but anyway, it worked.