1

I need to update likes array in blogSchema depending on whether it contains the creatorId string or not. If it does than I remove the string from the array, if it doesn't than I add it to the array. I tried my best to create a method for it, but it doesn't update the model. What would be the right way to update an array based on a condition?

const blogSchema = new mongoose.Schema({
...bla-bla,
likes:[String]
});
BlogPostSchema.statics.updateLikesForPost = async function(postId,creatorId) {
    const blogPost = this;
    return await new Promise(async (resolve,reject) => {
        try {
            const updatedPost = await blogPost.findById(postId).exec((err,blog) => {
                const index = blog.likes.indexOf(creatorId);
                if(index) {
                    blogPost.update({$push:{likes:creatorId}});
                } else {
                    blogPost.pull({$pull: {likes:creatorId}});
                }
            });
            resolve(updatedPost);
        } catch(e) {
            resolve(e.message);
        }
    }); 
};
Community
  • 1
  • 1
Umbrella
  • 1,085
  • 1
  • 14
  • 30

0 Answers0