【问题标题】:Unique Field in Meteor AutoFormMeteor AutoForm 中的唯一字段
【发布时间】:2016-04-29 13:37:35
【问题描述】:

我有一个带有以下字段的 Meteor AutoForm 集合架构,我正在努力使其独一无二。它不允许在相同的情况下使用相同的值,但是当我更改值的大小写时,值会被插入,那么如何防止插入不同大小写的重复值?

TestTESTTesT 都具有相同的咒语,因此不应插入。

我试过了:

Schemas.Organisation = new SimpleSchema({
    company: {
        type: String,
        max: 200,
        unique: true,
        autoValue: function () {
            if (this.isSet && typeof this.value === "string") {
                return this.value.toLowerCase();
            }
        },
        autoform:{
            label: false,
            afFieldInput: {
                placeholder: "Enter Company Name",
            }
        }
    }
  })

但它不允许我插入重复的值,而是在保存在数据库中时转换为全小写。那么如何保存用户输入的值,但值不应该有相同的拼写?

【问题讨论】:

    标签: javascript meteor meteor-autoform simple-schema


    【解决方案1】:

    这可以通过使用自定义客户端验证来实现。如果您不想将 Organisation 集合的所有文档发布给每个客户,您可以使用 asynchronous validation approach,例如:

    Organisations = new Mongo.Collection("organisations");
    
    Organisations.attachSchema(new SimpleSchema({
        company: {
            type: String,
            max: 200,
            unique: true,
            custom: function() {
                if (Meteor.isClient && this.isSet) {
                    Meteor.call("isCompanyUnique", this.value, function(error, result) {
                        if (!result) {
                            Organisations.simpleSchema().namedContext("insertCompanyForm").addInvalidKeys([{
                                name: "company",
                                type: "notUnique"
                            }]);
                        }
                    });
                }
            },
            autoValue: function() {
                if (this.isSet && typeof this.value === "string") {
                    return this.value.toLowerCase();
                }
            },
            autoform: {
                label: false,
                afFieldInput: {
                    placeholder: "Enter Company Name",
                }
            }
        }
    }));
    

    if (Meteor.isServer) {
      Meteor.methods({
        isCompanyUnique: function(companyName) {
          return Organisations.find({
            company: companyName.toUpperCase()
          }).count() === 0;
        }
      });
    }
    

    <body>
      {{> quickForm collection="Organisations" id="insertCompanyForm" type="insert"}}
    </body>
    

    这是MeteorPad

    【讨论】:

    • 我在寻找针对 _id 的自定义验证时偶然发现了这一点。我尝试了上述方法,似乎在发生验证错误并且我再次点击提交多次之后,我似乎遇到了错误。服务器日志说:调用方法'/aggrRouter_aaaContext_template_collection/insert'时出现异常错误:已经定义了一个名为'isAggrUnique'的方法我已经打开了一个关于相同here的新问题
    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2016-01-22
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    相关资源
    最近更新 更多