假设我有一个post包含以下 4 个字段的内容类型:
title (细绳)content (细绳)slug (细绳)author (关系)如何添加依赖于上述 4 个字段之一的值且用户不可编辑的第 5 个字段?比如说,我想要一个以wordCount字段中的单词数content作为其值的字段。我应该考虑探索哪个文件以合并此功能?
PS:就其价值而言,我正在使用 MongoDB Atlas 来满足我的数据库需求。
您必须wordCount在您的内容类型中创建您的属性。
然后在左侧菜单的内容管理器链接中,您将能够自定义编辑/创建页面的视图。在这里,您将能够从页面中禁用或删除该字段。
之后,您将必须进入./api/post/models/Post.js文件并更新以下功能。
如果您使用的是 NoSQL 数据库 (Mongo)
beforeSave: async (model) => {
if (model.content) {
model.wordCount = model.content.length;
}
},
beforeUpdate: async (model) => {
if (model.getUpdate().content) {
model.update({
wordCount: model.getUpdate().content.length
});
}
},
Run Code Online (Sandbox Code Playgroud)
如果您使用 SQL(SQLite、Postgres、MySQL)
beforeSave: async (model, attrs, options) => {
if (attrs.content) {
attrs.wordCount = attrs.content.length;
}
},
Run Code Online (Sandbox Code Playgroud)