Meteor:在新创建的用户上插入文档

时间:2014-10-22 10:13:36

标签: meteor

这可能比我听起来更简单。

我允许我的用户在登录时创建他的myprofile。这是存储在MyProfile = new Meteor.Collection('myprofile');中的文档。原则与LinkedIn完全相同...您登录,并填写个人资料表单,您所做的任何编辑只会更新一个文档。

在文档中会有一些字段,例如'摘要' ' newsInterest'和其他人,也是'所有者'这是用户ID。

1)如何使用'所有者'将文档插入MyProfile集合?字段是StartUp上新创建的用户的userId吗?

这是这个文档的数据,这些字段的值将被传递到myprofile页面。最初返回的值将是空白的,但是当用户键入时,在键入时,myprofile文档将被更新。

在客户端上按如下方式创建用户。现在这很好。

2)此外,如果有人在服务器上创建了用户,请提供任何链接。我调用了一种方法,将以下内容作为对象插入到Meteor.users.insert(object);中,但这不起作用。

Template.join.events({
'submit #join-form': function(e,t){
e.preventDefault();
Accounts.createUser({
  username: t.find('#join-username').value,
  password: t.find('#join-password').value,
  email: t.find('#join-email').value,
  profile:{
    fullname: t.find('#join-fullname').value,
summary: [],
newsInterest: [],
otherstuff: []
  }
});
Router.go('myprofile');
}
});

3 个答案:

答案 0 :(得分:2)

1)为了解决问题1,您有两种选择。

而不是像在规范化的MySQL数据库中那样为配置文件设置单独的集合。在已附加到用户集合中的对象的配置文件对象中添加用户配置文件数据。然后,您可以在Accounts.createUser function

的options参数中传入所需的值
Template.join.events({
  "submit #join-form": function (event) {
    event.preventDefault();
    var firstName = $('input#firstName').val(),
    lastName = $('input#lastName').val(),
    username = firstName + '.' + lastName,
    email = $('input#email').val(),
    password = $('input#password').val(),
    profile = {
      name: firstName + ' ' + lastName
    };
    Accounts.createUser({
      email: email,
      username: username,
      password: password,
      profile: profile
    }, function(error) {
      if (error) {
        alert(error);
      } else {
        Router.go('myprofile');
      }
    });
  }
});

这是一个使用jQuery获取值的示例,但是你的t.find应该同样正常。

如果您确实想要使用单独的集合,那么我建议在onCreateUser function(服务器端)内使用以下代码:

Accounts.onCreateUser(function(options, user) {
    user._id = Meteor.users._makeNewID();

    profile = options.profile;
    profile.userId = user._id;

    MyProfile.insert(profile);

    return user;
});

如果要在用户的个人资料字段中更新或添加其他数据,可以使用以下内容:

var newProfile = {
    summary: 'This summary',
    newsInterest: 'This newsInterest',
    otherstuff: 'Stuff'
};

Meteor.users.update(Meteor.userId, {$set: {profile: newProfile}});

或者,如果您选择以下单独的收集选项:

var newProfile = MyProfile.findOne(Meteor.userId);
newProfile.summary = 'This summary';
newProfile.newsInterest = 'This newsInterest';
newProfile.otherstuff = 'Stuff';

MyProfile.update(Meteor.userId, newProfile);

Haven没有测试过这个,所以让我知道我是否有任何语法/拼写错误,我会更新。

答案 1 :(得分:0)

使用服务器上的Accounts.onCreateUser回调可以轻松解决问题1 - 它为回调提供了用户对象,因此您可以从中获取userId并插入新的" myProfile"与那个主人。

正如Will Parker在下面指出的那样,用户文档此时实际上并没有_id,所以你需要创建一个并将其添加到user对象中回调返回。你可以这样做:

user._id = Meteor.users._makeNewID();

答案 2 :(得分:0)

Q2:您必须向服务器发送电子邮件,密码和配置文件对象,并使用相同的Accounts.createUser。一切正常。

相关问题