首页 > 解决方案 > 带有验证作者的 Model.findByIdAndUpdate()

问题描述

我想用验证作者更新类别

我有两个模型:

Category: { id, title, description, author } //author contains userId

User: { id, name, categories } //categories contain categoryId.

我要检查:只有作者可以更新作者的类别,如果你不是作者,你不能更新这个类别。我该怎么做?

我的代码没有findByIdAndUpdate()

在此处输入图像描述

我的代码findByIdAndUpdate()

const update = async (id, updatedCategory, authorId) => {
    try {
        const { title, description } = updatedCategory
        const query = {
          ...(title && { title }),
          ...(description && { description }),
          date: Date.now(),
        }

        let category = await Category.findByIdAndUpdate(id, query, 
        (error, doc) => {
            return doc
        }

        if (!category) throw "Can not find category"
        // How to validate with authorId?
        return category
    } catch (error) {
        throw error
    }
}

标签: javascriptmongoose

解决方案


您需要对查询进行少量修改。而不是findByIdAndUpdate使用findOneAndUpdate.

const update = async (id, updatedCategory, authorId) => {
    try {
        const { title, description } = updatedCategory
        const query = {
          ...(title && { title }),
          ...(description && { description }),
          date: Date.now(),
        }

        let category = await Category.findOneAndUpdate({_id:id, author:authorId}, query, 
        (error, doc) => {
            return doc
        }

        if (!category) throw "Can not find category"
        // How to validate with authorId?
        return category
    } catch (error) {
        throw error
    }
}

推荐阅读