2014-10-03 50 views
0

有沒有辦法從調用函數中檢索傳入的對象的ID。我已經將該對象插入到方法中的集合中,所以這很好。但是,我也想檢索此對象的Id並將其插入到當前用戶profile.postcreated字段中。檢索從調用函數傳遞的對象的ID

我的通話功能:

Template.createpost.events({ 
'submit form#createpost': function(e, tmpl) { 
e.preventDefault(); 
var insertpost = { 
field: $("#someId").val(); 
} 
Meteor.call('insertPostData', insertpost); 
} }); 

方法功能:

Meteor.methods({ 
'insertPostData': function(insertPostData){ 
    return AllPosts.insert(insertPostData); //THIS WORKS FINE 
    Meteor.users.update({ _id: Meteor.userId() }, { $addToSet: { 'profile.postcreated': **objectsId** }} 
); 
}); 
+0

難道你不能通過你正在創建的insertpost對象來傳遞它嗎?否則,只傳遞字段而不是它的價值,這樣你可以訪問它的價值,屬性,甚至操縱它? – Gavin 2014-10-03 13:49:41

回答

2

Collection.insert返回插入的對象_id,所以你只需要把它保存爲以後使用的變量。

Meteor.methods({ 
    'insertPostData': function(insertPostData){ 
    var user=Meteor.users.findOne(this.userId); 
    // assuming postcreated is something like ["POSTID"] 
    if(user.profile.postcreated.length>=1){ 
     return; 
    } 
    var postId=AllPosts.insert(insertPostData); 
    Meteor.users.update(this.userId,{ 
     $addToSet:{ 
     'profile.postcreated':postId 
     } 
    }); 
    return postId; 
    } 
}); 
+0

這是完美的saimeunt! – meteorBuzz 2014-10-03 14:07:50

+0

如果postcreated字段已填充,如何防止此插入?下面的代碼關閉了嗎? ... if(this.userId()。profile.postcreated.find()。count()<1){.. insertion code} – meteorBuzz 2014-10-03 14:44:16

+0

編輯我的答案,這是我該怎麼做。 – saimeunt 2014-10-03 15:19:25

相關問題