javascript - 带有验证作者的 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
}
}
解决方案
您需要对查询进行少量修改。而不是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
}
}
推荐阅读
- node.js - Visual Studio Code 不建议任何 Node.js 语法
- r - 如何使用带有 Rscript 的 API 密钥在 Postman 中对自己进行身份验证
- python - 满足条件时终止的循环
- javascript - Openlayers 悬停渲染顺序,悬停特征渲染在所有其他特征之上
- c - 在 Visual Studio Code(或 VS2019)中运行 C 程序
- c# - 导出 DataTable C# 以访问 - 慢问题 - 100 万行和 29 列
- java - 使用管道直径计显示特殊字符
- github - 当内容存储在 docs 文件夹中时,如何通过自定义域提供 Github 页面?
- algorithm - 来自“编译器 - 原理、技术和工具”(又名 Dragon Book)的练习 4.2.8
- c - 使用指针将输入读入数组时如何正确使用scanf()?