2016-04-01 30 views
1

這個Meteor代碼工作正常,但我想問問Meteor是幹什麼的,或者這是一種不可預測的副作用,可能會在稍後的某些情況下發生變化。
的事情是,當我做
DisplayCol.insert({action: 'task1', element: 'p', value: value_variable});
流星還插入了正確的用戶ID(使用2個不同的瀏覽器登錄的2個不同的用戶),我沒有明確包含在文檔中。userId奇蹟般地進入文檔

上面的代碼行是在從Meteor方法調用的服務器端函數中。

這裏是相關信息;

//lib/collection.js
DisplayCol = new Mongo.Collection('displayCol');

//server.js

Meteor.publish('displayCol', function() { 
    return DisplayCol.find({userId: this.userId}); 
}); 
DisplayCol.before.insert(function (userId, doc) { 
    doc.userId = userId; 
}); 

在收集鉤的docs>其他備註>第二項目符號段落說:

userId可用於查找和查找在發佈功能中調用的一個查詢。

但是這是一個collection.insert。所以我應該在文檔中明確包含userId還是讓集合掛鉤實現其隱藏的魔力?謝謝

回答

2

不,這個代碼沒有隱藏的魔法,你的before鉤子在文檔中插入userId字段。

當你做一個insert這樣,

DisplayCol.insert({action: 'task1', element: 'p', value: value_variable}); 

doc,你要插入的{ action: 'task1', element: 'p', value: value_variable }

因爲,你有這樣的掛鉤,

DisplayCol.before.insert(function (userId, doc) { 
    doc.userId = userId; 
}); 

它改變了doc前插入收藏。所以上面的鉤子將改變你的doc{action: 'task1', element: 'p', value: value_variable, userId: 'actual-user-id' }

預期的行爲。

就問題的另一點,

用戶標識可查找和發佈功能中調用了該 查詢findOne。

此前userId參數在findfindOne返回null,所以用戶需要通過userId作爲參數如在本comment提及。其他注意事項提到黑客不再是必需的。它與將userId字段插入收集文檔無關。

要進行快速測試,請刪除上面的DisplayCol.before.insert掛鉤,在新插入的文檔中不會看到userId字段。

UPDATE

只是進一步明確您的疑問,從文檔的第4點,你提供

這是很正常的用戶id有時不可用鉤在一些 回調情況。例如,如果在沒有用戶上下文的情況下從服務器發起更新 ,服務器當然不會是 能夠提供任何特定的用戶標識。

這意味着如果在服務器上插入或更新文檔,將沒有用戶與服務器關聯,那麼userId將返回null。

你也可以自己檢查源代碼here。檢查CollectionHooks.getUserId方法,它使用Meteor.userId()獲取userId

CollectionHooks.getUserId = function getUserId() { 
    var userId; 

    if (Meteor.isClient) { 
    Tracker.nonreactive(function() { 
     userId = Meteor.userId && Meteor.userId(); // <------- It uses Meteor.userId() to get the current user's id 
    }); 
    } 

    if (Meteor.isServer) { 
    try { 
     // Will throw an error unless within method call. 
     // Attempt to recover gracefully by catching: 
     userId = Meteor.userId && Meteor.userId(); // <------- It uses Meteor.userId() to get the current user's id 
    } catch (e) {} 

    if (!userId) { 
     // Get the userId if we are in a publish function. 
     userId = publishUserId.get(); 
    } 
    } 

    return userId; 
}; 
+0

確定,具體來說,函數中的userId參數傳遞給鉤子,它如何知道要使用哪個userId? –

+1

@FredJ。它使用當前用戶的ID。類似於Meteor.userId()。 – Kishor

+0

@FredJ。更新了答案。 – Kishor

相關問題