如何在Sanity中限制Schema文档数量?仅允许单个Blog条目
实现单条目Blog文档的可行方案
你不能移除type: 'document',这是Sanity文档类型Schema的必填属性,删掉必然报错。要实现只能存在一个Blog文档,有两种实用方案:
方案一:添加文档验证规则,阻止创建多个条目
在你的Blog Schema中加入自定义验证逻辑,检查已有Blog文档的数量,超过1个就阻止创建:
export default { name: 'blog', type: 'document', title: 'Blog', // 新增验证规则 validation: (Rule) => Rule.custom(async (document, context) => { // 查询所有已存在的Blog文档 const existingBlogs = await context.client.fetch('*[_type == "blog"]') // 如果是新建文档(无_id)且已有至少1个Blog,返回错误提示 if (!document._id && existingBlogs.length >= 1) { return '只能创建一个Blog文档' } return true }), fields: [ { name: 'title', title: 'Title', type: 'string', }, { name: 'content', title: 'Content', type: 'array', of: [{ type: 'block' }], }, ], }
这个验证会在用户尝试新建第二个Blog时触发错误,阻止重复创建。
方案二:自定义工作室结构,隐藏创建入口
通过配置Sanity工作室的结构,直接指向唯一的Blog文档,彻底隐藏新建按钮:
在你的工作室配置文件(通常是sanity.config.js)中修改structure部分:
import { defineConfig } from 'sanity' import { StructureBuilder } from 'sanity/structure' export default defineConfig({ // 其他配置项(如projectId、dataset等)保持不变 structure: (S: StructureBuilder) => S.list() .title('内容管理') .items([ // 自定义Blog条目,直接打开固定ID的文档 S.listItem() .title('Blog') .child( S.document() .schemaType('blog') .documentId('blog-singleton') // 固定唯一文档ID ), // 保留其他文档类型的列表,排除原有的Blog列表项 ...S.documentTypeListItems().filter(item => item.getId() !== 'blog'), ]), })
这样配置后,工作室侧边栏不会显示Blog的文档列表,用户点击Blog选项会直接进入唯一的文档编辑页面——如果这个ID为blog-singleton的文档不存在,会自动创建,用户无法新建其他Blog文档。
建议:可以同时使用两种方案,既通过验证规则兜底防止意外创建,又通过结构优化提升用户体验。
内容的提问来源于stack exchange,提问作者solalilali
相关产品推荐
相关产品推荐

