meteor.js – 将数组推送到用户集合

CONTEXT

我刚刚创build了一个新用户,现在想把值传递给我的用户集合中的一个数组。 我正在使用以下代码:

//User Schema - in User Collection Schema.User = new SimpleSchema({ userEvents: { type: [String], optional: true }, [...] //User Methods - in server/methods Meteor.methods({ 'addUserEvent': function (organizerId, params) { console.log(organizerId); console.log(params); Meteor.users.update({ organizerId: organizerId },{ $set:params }); } }); //Create new event and add ID of event to current user - in events controller EventsController.events({ 'click #mainEventType' : function(event) { var organizerId = Accounts.userId(); var eventStatus = "processStarted"; //get value from selection var mainEventType = event.target.alt; var eventParams = { organizerId: organizerId, mainEventType: mainEventType, eventStatus: eventStatus } //Insert Event and use callback to get the id of the even you just inserted Meteor.call('addEvent', eventParams, function(error, result){ //use session set to store value of user id and event id Session.set("organizerId", Accounts.userId()); Session.set("myEventId", result) console.log("organizer ID: " + Session.get("organizerId")); console.log("usereventId: " + Session.get("myEventId")); }); eventId = [] eventId.push(Session.get("myEventId")) //set params for user var userParams = { userEvents: eventId } console.log(userParams) Meteor.call('addUserEvent', Session.get("organizerId"), userParams); }, [...] 

问题

用户方法中的两个控制台日志会生成正确的值(即刚刚创build的事件和当前用户的事件)。 但是,我无法将这些添加到用户集合中。 通过控制台和terminal(meteor蒙哥)来看,它显示该领域还没有被填补。 而且,addUserEvent方法中的console.log永远不会被调用,所以在那里可能有问题。

你正在调用客户端的两个方法。 它们被asynchronous调用,所以当第一个调用仍在执行时,第二个调用已经被触发。 这就是为什么你有callback。 为了解决你的代码,在addEvent的callback中有第二个addUserEvent的调用。 在调用addUserEvent之前检查error

像这样的东西:

 //Insert Event and use callback to get the id of the even you just inserted Meteor.call('addEvent', eventParams, function(error, result){ //use session set to store value of user id and event id Session.set("organizerId", Accounts.userId()); Session.set("myEventId", result) console.log("organizer ID: " + Session.get("organizerId")); console.log("usereventId: " + Session.get("myEventId")); if (!error) { eventId = [] eventId.push(Session.get("myEventId")) //set params for user var userParams = { userEvents: eventId } console.log(userParams) Meteor.call('addUserEvent', Session.get("organizerId"), userParams); } }); 

顺便说一句,如果你想访问this ,像这样添加.bind(this)到callback:

 Meteor.call('addEvent', eventParams, function(error, result){ // Your callback function body }.bind(this)); 

UPDATE

对于有类似问题的任何人,问题是你需要使用$push而不是$set 。 这是推送function应该是这样的:

 'addUserEvent': function (organizerId, params) { Meteor.users.update({ _id: organizerId } , { $push: params }); }