我有一个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",
            }
        }
    }
  })

但这不是让我插入重复的值,而是在保存到数据库时将其转换为所有小写字母。因此,如何保存用户输入的值,但值不应具有相同的拼写?

最佳答案

这可以通过使用自定义客户端验证来实现。如果您不想将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

关于javascript - meteor AutoForm中的唯一字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34955421/

10-11 16:49