1

我想在服務器上使用觀察我的一個集合,但我需要獲取userId, 我試圖使用this.userIdMeteor.userId(),但不工作!請參閱下面的代碼以獲取更多詳細信息和錯誤消息 如何解決它?如何在觀察回調中獲取userId

Messages.find({state:"outbox"}).observe({ 
    added: (doc) => { 
    console.log(" observe "); 
     console.log("userId : " + this.userId); // undefined 
     console.log("Meteor.userId(): " + Meteor.userId()); // "Exception in queued task: Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions." 
     //....... 
    } 
}); 

感謝您的關注。

+0

這是從發佈函數中調用,還是僅在服務器啓動時全局調用? –

回答

2

observe回調中,this關鍵字不指向發佈對象(它指向的光標相關查詢),因此它不具有userId財產。

您可以創建一個封閉,使userId提供給函數在出版物本身的機身採用

const userId = this.userId; 

,然後只需在回調使用(如userId)。