【问题标题】:userId from onCreateUser gets deleted in associated records来自 onCreateUser 的 userId 在关联记录中被删除
【发布时间】:2015-03-21 00:40:37
【问题描述】:

在创建新用户时,我需要创建一些通过用户 ID 引用用户的新文档

Accounts.onCreateUser(function(options, user) {
  console.log(user);

  var google = user.services.google;
  var tokens = {
    accessToken: google.accessToken,
    // refreshToken: google.refreshToken
  };

  if (tokens.accessToken) {
    Meteor.call('createChannel', user._id, tokens, function(error, result) {
      if (error) {
        throw error;
      }
    });
  }
  return user;
});

createChannel 方法中,我使用传入的 id user._id 来设置一些引用用户文档的文档。

createChannel: function(userId, tokens) {
    console.log(userId);

    var missionId = Meteor.call('createDefaultMission', userId);
    ... 

  /* Creates a new mission with default values
   */
  createDefaultMission: function(userId) {
    doc = {
      _id: Random.id(),
      userId: userId,
      name: 'My Mission',
    };

    var missionId = Missions.insert(doc);
    return missionId;
  },

问题是,在这种情况下,任务记录在创建后没有任何 userId 字段。使用 SimpleSchema 时,我收到 User is required 错误。

知道这是为什么吗?

更新

createDefaultMission: function(userId) {
    doc = {
      _id: Random.id(),
      userId: userId,
      name: 'My Mission',
    };

    console.log(doc); <----- this logs the above with the userId field filled
    console.log(Meteor.users.findOne(userId)); <----- this finds the user with the above ID

    var missionId = Missions.insert(doc); <---- this failed, userId field is not present
    return missionId;
  },

【问题讨论】:

    标签: meteor


    【解决方案1】:

    userId 直到 onCreateUser 完成执行后才会生成。有关详细信息,请参阅this issue。您可以通过使用collection hook 来解决此问题,如下所示:

    Meteor.users.after.insert(function(userId, doc) {
      var google = doc.services.google;
      var tokens = {accessToken: google.accessToken};
      Meteor.call('createChannel', userId, tokens);
    });
    

    【讨论】:

    • 好的,我这样做了,但仍然没有将 userId 与其余部分一起插入。更新帖子
    • 你写的似乎不可能。我怀疑您查询集合的方式不正确。我建议做一个console.log(missionId),然后通过该ID查找任务。或者,只需重置您的数据库,这样您就可以执行Missions.findOne()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2021-11-14
    • 2011-04-29
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多