我尝试使用以下代码将一个对象添加到作为集合条目中的键的对象数组,但我收到一个奇怪的响应“插入失败:错误:需要标题”。我在 Meteor 上使用简单的模式/自动表单。
有人以前遇到过这个问题(并有解决方案)吗?
Template.dashboard.events({
'click .requestinvite'(e,t) {
Posts.insert({ _id : $(e.currentTarget).attr('_id')},
{$push: { invitesRequested : {username : Meteor.userId()} }}
);
}
});
这是coffeescript中相关的简单模式
Schemas.Posts = new SimpleSchema
title:
type:String
max: 60
optional: true
content:
type: String
optional: false
autoform:
rows: 5
createdAt:
type: Date
autoValue: ->
if this.isInsert
new Date()
updatedAt:
type:Date
optional:true
autoValue: ->
if this.isUpdate
new Date()
invitesRequested:
type: [Object]
optional: true
defaultValue: []
owner:
type: String
regEx: SimpleSchema.RegEx.Id
autoValue: ->
if this.isInsert
Meteor.userId()
autoform:
options: ->
_.map Meteor.users.find().fetch(), (user)->
label: user.emails[0].address
value: user._id
最佳答案
首先,根据正确的 JavaScript 分配标准,您在代码中犯了错误。
如果您的代码被黑客攻击并且在没有分配任何 id 的情况下调用单击事件怎么办?
您的代码必须如下。
Template.dashboard.events({
'click .requestinvite'(e,t) {
var id = $(e.currentTarget).attr('_id');
if(id){
Posts.insert(
{
_id : id
},
{
$push: {
invitesRequested : {username : Meteor.userId()}
}
}
);
} else {
//do something here when you don't have id here, or the `click` event is hacked on UI to work without id'
}
}
});
由于您的 SimpleSchema 给出了有关 title
的错误字段,如果不是必填,请使用optional : true
在定义title
时字段。
例如
title: {
type: String,
label: "Title",
optional: true //<---- do this
}
NOTE: By default, all keys are required. Set
optional: true
to change that.
关于javascript - 插入失败: Error: Title is required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46136101/