我想用验证作者更新类别
我有两个模型:
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
}
}
答案 0 :(得分:0)
您需要在查询中进行一些修改。代替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
}
}