2017-09-09 94 views
0

我想添加一個對象到一個對象數組,這是一個集合項中的一個鍵,下面的代碼,但我得到一個奇怪的響應「插入失敗:錯誤:標題是必需的「。我在流星上使用簡單的模式/ autoform。插入失敗:錯誤:標題是必需的

有沒有人遇到過這個(並有一個解決方案)?

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 
+1

你的簡單模式必須有一個標題是必需的 – Mikkel

+0

是的,好像簡單模式阻止插入,你需要允許標題。 – Deano

+0

請在這裏發佈您的SimpleSchema。提供足夠的細節,以免我們浪費時間在你的問題上。 –

回答

1

首先,按照適當的JavaScript分配的標準,你在你的代碼做的失誤。

如果您的代碼遭到黑客入侵併且沒有分配任何標識而調用click事件會怎麼樣?

您的代碼必須如下。

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場,如果它不是強制性的,那麼好心的定義title場點使用optional : true

例如

title: { 
    type: String, 
    label: "Title", 
    optional: true //<---- do this 
} 

NOTE: By default, all keys are required. Set optional: true to change that.

+0

上面添加了相關的simpleschema,導致出現以下錯誤 'insert failed:Error:Content is required' – Silicabello

+0

事件鏈現在很明顯,它似乎試圖爲Posts創建一個新的添加項?我試圖推送到Posts中現有條目中的invitesRequested值數組,爲什麼試圖創建一個新的Posts條目?我應該使用不同的功能,而不是插入? – Silicabello

+0

如果它幫助你實現你的答案,接受我的答案是一個簡單的要求。接受答案激勵我們回答越來越多的人,引導他們學習新的東西。 –

0

答案是使用Posts.update代替。但Ankur Soni的帖子引導我朝着正確的方向排除故障。