有条件地使用mongoose

时间:2017-09-02 13:00:07

标签: node.js mongodb mongoose mongodb-query database

我需要在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);
        }
    }); 
};

0 个答案:

没有答案