【问题标题】:How to add pre-hook in keystonejs?如何在keystonejs中添加预挂钩?
【发布时间】:2019-06-16 14:35:40
【问题描述】:

我想添加多个选择选项字段。但是不允许多选的文档state。但建议对这种情况进行预挂钩。

在模型中存储一个字符串或数字。显示为选择字段 管理界面。不允许选择多个项目。如果你 要提供多个值,可以使用 TextArray 或 NumberArray, 尽管两者都没有相同的约束输入。 您可以限制 使用预保存挂钩的选项。

我搜索 pre-hook,但它似乎来自猫鼬。就我而言,我使用 Keystone 创建模型,以便可以在管理页面中使用它

var keystone = require('keystone');
var Types = keystone.Field.Types;

var MyModel = new keystone.List('MyModel');

MyModel.add({
    aField: { type: Types.TextArray, required: false, initial: true },
});

那么我该如何创建预挂钩呢?例如,我想将 TextArray 限制为 ('a','b','c')?

【问题讨论】:

  • Keystone 模型 Mongoose 模型。您可以添加 pre 钩子,方法与在 Mongoose 中完全相同。

标签: keystonejs


【解决方案1】:

我已经设置了这样的预保存挂钩(或类似的东西。没有测试这段代码)。

var keystone = require('keystone');
var Types = keystone.Field.Types;

/**
 * Musician Model
 * ==========
 */

var Musician = new keystone.List('Musician', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true },
});

Musician.add({
    title: { type: String, required: true },
    published: { type: Types.Boolean, default: false },
    musicianId: { type: String, note: noteUpdateId },    
});

Musician.schema.pre('save', function (next) {
    console.log(this.title);
    console.log(this.isNew);
    if (this.isNew) {
        // generates a random ID when the item is created
        this.musicianId = Math.random().toString(36).slice(-8);
    }
    next();
});

Musician.defaultColumns = 'title, published, musicianId';
Musician.register();

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2017-04-04
    • 1970-01-01
    • 2012-08-23
    相关资源
    最近更新 更多