如何向 Strapi 中的内容类型添加非用户可编辑字段? [英] How to add a non-user-editable field to a content type in Strapi?
问题描述
假设我有一个带有以下 4 个字段的 post
内容类型:
Say I have a post
content type with the following 4 fields:
title
(字符串)content
(字符串)slug
(字符串)作者
(关系)
title
(string)content
(string)slug
(string)author
(relationship)
如何添加依赖于上述 4 个字段之一的值且用户不可编辑的第 5 个字段?比如说,我想要一个 wordCount
字段,其中 content
字段中的字数作为其值.为了合并此功能,我应该考虑探索什么文件?
How can I add a 5th field that depends on one of the above 4 fields for its value and isn't user-editable? Say, I wanted a wordCount
field with the number of words in the content
field as its value. What file should I consider exploring in order to incorporate this functionality?
P.S.:就其价值而言,我正在使用 MongoDB Atlas 来满足我的数据库需求.
P.S.: For what it's worth, I'm using MongoDB Atlas for my database needs.
推荐答案
您必须在您的内容类型中创建您的 wordCount
属性.
You will have to create your wordCount
attribute in your content type.
然后在左侧菜单的内容管理器链接中,您将能够自定义编辑/创建页面的视图.您可以在此处禁用或删除页面上的字段.
Then in the content manager link in the left menu, you will be able to custom the view of your edit/create page. Here you will be able to Disable or Remove the field from the page.
之后,您必须进入./api/post/models/Post.js
文件并更新以下函数.
After that you will have to go in the ./api/post/models/Post.js
file and update following functions.
如果您使用的是 NoSQL 数据库 (Mongo)
If you are using NoSQL database (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
});
}
},
如果您使用 SQL(SQLite、Postgres、MySQL)
If you are using SQL (SQLite, Postgres, MySQL)
beforeSave: async (model, attrs, options) => {
if (attrs.content) {
attrs.wordCount = attrs.content.length;
}
},
这篇关于如何向 Strapi 中的内容类型添加非用户可编辑字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!