如何使用autovalue在SimpleSchema Meteor中定义子文档而不将其插入每个父文档插入?

时间:2014-10-23 09:31:05

标签: javascript node.js meteor meteor-autoform

我尝试使用子文档为集合定义模式,父文档和子文档都具有应在插入时设置的autovalue字段。 问题是,当我尝试插入新的父文档(没有任何子文档)时,我收到一条错误,指出子文档字段是必需的。

以下是重现问题的完整代码:

main.js

ChatRooms = new Meteor.Collection("chatRooms");

schema_ChatRooms_ChatMesssage = new SimpleSchema({
    userId: {
        type: String,
        label: "User ID",
        autoValue: function() {
            if (this.isInsert) {
              if (! this.isFromTrustedCode) {
                return this.userId;
              }
            } else {
              this.unset();
            }},
        autoform: { omit: true }
    },
    content: {
        type: String,
        label: "Content",
        max: 1000,
        min: 1
    },
    creationDate: {
        type: Date,
        label: "Created On",
        autoValue: function() {
            if (!this.isSet) {
                return new Date();
            }
            else {
              this.unset();
            }},
        autoform: { omit: true }
    }
});

schema_ChatRoom = new SimpleSchema({
    name: {
        type: String,
        label: "Name",
        max: 50,
        min: 1
    },
    isPublic: {
        type: Boolean,
        label: "Public"
    },
    creationDate: {
        type: Date,
        label: "Created On",
        autoValue: function() {
            if (!this.isSet) {
                return new Date();
            }
            else {
              this.unset();
            }},
        autoform: { omit: true }
    },
    // Sub Documents
    chatMessages: {
        type: schema_ChatRooms_ChatMesssage,
        label: "Chat Messages",
        optional: true,
        autoform: { omit: true }
    }
});

ChatRooms.attachSchema(schema_ChatRoom);

if (Meteor.isClient) {
    AutoForm.addHooks(null, {
        onError: function(operation, error, template) {
                    alert(operation.toString() + " : " + error.toString());
                }
    });
} 

main.html中

<head>
  <title>TestSubDoc</title>
</head>

<body>
  <h1>Create</h1>

  {{> quickForm collection="ChatRooms" id="chatRooms_create_form" type="insert"}}
</body>

我尝试添加&#34;可选:true&#34; to&#34; chatMessages&#34;但它没有解决它。 即使没有包含子文档,子文档autovalue仍然会被执行并创建一个包含生成值的新子文档。

如何使用具有自动值的子文档正确创建文档?

1 个答案:

答案 0 :(得分:0)

可能你需要将schema_ChatRooms_ChatMesssage中的所有字段设为可选,并由autoform设置。

相关问题