我需要在likes
中更新blogSchema
数组,具体取决于它是否包含creatorId
字符串。如果它比我从数组中删除字符串,如果它不是我添加到数组。我尽力为它创建一个方法,但它不会更新模型。根据条件更新数组的正确方法是什么?
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);
}
});
};