[英]How to define a subdocument in SimpleSchema Meteor with an autovalue without inserting it on each parent document insert?
I'm trying to define a schema for a collection with a sub document, both parent and sub documents have autovalue fields that should get set on inserts. 我正在尝试为带有子文档的集合定义一个架构,父文档和子文档都具有应在插入项上设置的自动值字段。 The problem is that when I try to insert a new parent document (without any sub documents) I get an error stating that the sub-document fields are required.
问题是当我尝试插入新的父文档(不包含任何子文档)时,出现错误消息,指出子文档字段是必需的。
Here is the full code to reproduce the problem: 这是重现该问题的完整代码:
main.js 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 main.html中
<head>
<title>TestSubDoc</title>
</head>
<body>
<h1>Create</h1>
{{> quickForm collection="ChatRooms" id="chatRooms_create_form" type="insert"}}
</body>
I've tried adding an "optional: true" to "chatMessages" but it didn't solve it. 我试过在“ chatMessages”中添加一个“ optional:true”,但没有解决。 It seems like even when a sub-document is not included the sub-document autovalue still gets executed and creates a new subdocument with the generated values.
似乎即使不包含子文档,该子文档自动值仍然会执行并使用生成的值创建一个新的子文档。
What can I do to properly create a document with sub-documents that have auto values? 如何正确地创建带有自动值的子文档的文档?
可能您需要将schema_ChatRooms_ChatMesssage中的所有字段设置为可选,并通过自动形成功能将其忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.