ama*_*ouq 1 javascript mongodb meteor meteor-accounts
我在创建帐户,发布字段和订阅该出版物时为我的用户添加自定义字段,但我Meteor.user().customField无法在客户端访问该字段.
所以在我imports/api/users/users.js添加以下代码片段:
import { Random } from 'meteor/random'
Accounts.onCreateUser((options, user) => {
const cond = assignUserCondition();
user.enterTime= new Date();
user.page = null;
user.passedQuiz= false;
user.exitStatus=null;
user.quizAttempts= 0;
user.condition= cond;
user.avatar= null;
user.score= 0;
user.bonus= 0;
user.lobbyTimeout= LOBBY_TIMEOUT;
user.gameId= null;
user.condInfo = {name: cond,
groupSize: (cond+'GROUPS_SIZE').split('.').reduce((o, i) => o[i], CONDITIONS_SETTINGS),
bonusConversion: (cond+'BONUS_CONVERSION').split('.').reduce((o, i) => o[i], CONDITIONS_SETTINGS),
N_ROUNDS: (cond+'N_ROUNDS').split('.').reduce((o, i) => o[i], CONDITIONS_SETTINGS),
};
return user;
});
Run Code Online (Sandbox Code Playgroud)
然后,从meteor mongo我验证创建的用户确实有我添加的新自定义字段.现在,在 imports/api/users/server/publications.js我有以下片段:
import {Meteor} from 'meteor/meteor'
Meteor.publish('users.user', function(currentUser) {
let user= Meteor.users.find({_id:currentUser}, {
fields: {
_id: 1,
enterTime: 1,
page: 1,
passedQuiz: 1,
exitStatus: 1,
quizAttempts:1,
condition:1,
avatar: 1,
score:1,
bonus: 1,
lobbyTimeout: 1,
gameId: 1,
conditionInfo: 1
}
});
if ( user ) {
return user;
}
return this.ready();
});
Run Code Online (Sandbox Code Playgroud)
另外,在我imports/startup/client/index.js的订阅中:
Tracker.autorun(function(){
Meteor.subscribe('users.user');
});
Run Code Online (Sandbox Code Playgroud)
但是,在客户端,console.log(Meteor.user())只显示_id和username没有任何自定义字段.
您没有currentUser从您的客户端传递参数subscribe.然而,这是严格的禁忌,因为客户端不受信任(有人可以轻松地向_id您的方法发送不同的用户).将您的出版物改写为:
import {Meteor} from 'meteor/meteor'
Meteor.publish('users.user', function() {
if (this.userId) {
return Meteor.users.find(this.userId, {
fields: {
_id: 1,
enterTime: 1,
page: 1,
passedQuiz: 1,
exitStatus: 1,
quizAttempts:1,
condition:1,
avatar: 1,
score:1,
bonus: 1,
lobbyTimeout: 1,
gameId: 1,
conditionInfo: 1
}
});
}
return this.ready();
});
Run Code Online (Sandbox Code Playgroud)