Meteor - 缺少用户名Meteor.users.findOne();或Meteor.users();

时间:2022-04-13 16:59:38

Upon submit of a post, the current user does not seem to be recognised and username appears as blank. The submit html has {{author}} to display the user who wrote the post.

提交帖子后,似乎无法识别当前用户,并且用户名显示为空白。提交html有{{author}}来显示撰写帖子的用户。

Heres the results when I type the following in the console:

当我在控制台中键入以下内容时,会显示结果:

1)user.username

=> result user is undefined.

=>结果用户未定义。

2)Meteor.users.find();

=> LocalCollection.Cursor {collection: LocalCollection, sorter: null, _selectorId: undefined, matcher: Minimongo.Matcher, skip: undefined…}

=> LocalCollection.Cursor {collection:LocalCollection,sorter:null,_selectorId:undefined,matcher:Minimongo.Matcher,skip:undefined ...}

3) Meteor.users.findOne();

=> Object {_id: "P3ocCTTdvi2o3JApf", profile: Object}

=> Object {_id:“P3ocCTTdvi2o3JApf”,profile:Object}

compared to the working version (Note my version is missing username)

与工作版本相比(注意我的版本缺少用户名)

=> Object {_id: "XHXPebzjg5LM5tNAu", profile: Object, username: "Bruno"}

=> Object {_id:“XHXPebzjg5LM5tNAu”,profile:Object,username:“Bruno”}

In post.js collection (in the lib folder - shared with both client and server), I have:

在post.js集合中(在lib文件夹中 - 与客户端和服务器共享),我有:

Meteor.methods({
  postInsert: function(postAttributes) {
    check(this.userId, String);           //check(Meteor.userId(), String);
    check(postAttributes, {
      title: String,
      message: String
    });
    var user = Meteor.user();
    var post = _.extend(postAttributes, {
      userId: user._id, 
      author: user.username
    });
    var postId = Posts.insert(post);
    return {_id: postId};
  },

There are also no other references to author in the Discover Meteor tutorial, and it worked. However mine doesnt work. This problem seems to have started after I added UserAccounts package. Or perhaps a folder location issue?

在Discover Meteor教程中也没有其他对作者的引用,并且它有效。然而,我的工作不起作用。添加UserAccounts包后,似乎已经开始出现此问题。或者可能是文件夹位置问题?

Update [11 May 2015]

更新[2015年5月11日]

I realised that when using the original ui-accounts that came with Meteor, it has the username field because the sign up link that came with {{> login}} uses username + password. Theres no email address involved.

我意识到当使用Meteor附带的原始ui-accounts时,它有用户名字段,因为{{> login}}附带的注册链接使用用户名+密码。没有电子邮件地址。

UserAccounts on the other hand doesnt have this username field. Its either email/pw or social login. So perhaps someone guide me on how to have username (either as separate field or derived from email) from email/pw and social network button login/signin as a start? Then Ill try to fiddle from there.

另一方面,UserAccounts没有此用户名字段。它的电子邮件/ pw或社交登录。所以也许有人指导我如何从电子邮件/ pw和社交网络按钮登录/登录作为开始使用用户名(作为单独的字段或从电子邮件派生)?然后,我试图摆弄那里。

code for UserAccounts

UserAccounts的代码

router.js

//Iron router plugin to ensure user is signed in
AccountsTemplates.configureRoute('ensureSignedIn', {
  template: 'atTemplate',     //template shown if user is not signed in
  layoutTemplate: 'atLayout'  //template for login, registration, etc
});

Router.plugin('ensureSignedIn', { //Don't require user logged in for these routes
  except: ['login', 'register']   //can use only: too 
});

AccountsTemplates.configureRoute('signIn', {  //login
  name: 'login',
  path: '/login',
  template: 'atTemplate',
  layoutTemplate: 'atLayout',
  redirect: '/'
});

AccountsTemplates.configureRoute('signUp', {  //registration
  name: 'register',
  path: '/register',
  template: 'atTemplate',
  layoutTemplate: 'atLayout',
  redirect: '/'
});

and under config.js (server side)

并在config.js下(服务器端)

3 个解决方案

#1


From the Useraccounts doc, Try this:

从Useraccounts文档中,试试这个:

if (Meteor.isServer){
    Meteor.methods({
        "userExists": function(username){
            return !!Meteor.users.findOne({username: username});
        },
    });
}

AccountsTemplates.addField({
    _id: 'username',
    type: 'text',
    required: true,
    func: function(value){
        if (Meteor.isClient) {
            console.log("Validating username...");
            var self = this;
            Meteor.call("userExists", value, function(err, userExists){
                if (!userExists)
                    self.setSuccess();
                else
                    self.setError(userExists);
                self.setValidating(false);
            });
            return;
        }
        // Server
        return Meteor.call("userExists", value);
    },
});

This will add the username field to your login/register forms and check for username conflicts when registering new users.

这会将用户名字段添加到您的登录/注册表单中,并在注册新用户时检查用户名冲突。

The top part is server code the bottom part is common code, so you could place this whole snippet in project/lib/ folder, or place the method with the rest of your methods, depending on how your structuring your project.

顶部是服务器代码,底部是公共代码,因此您可以将整个代码段放在project / lib /文件夹中,或者将方法与其余方法放在一起,具体取决于构建项目的方式。

Use the following to have the username field show up first instead of last on the register form:

使用以下命令在注册表单中首先显示用户名字段而不是最后一个:

var pwd = AccountsTemplates.removeField('password');
AccountsTemplates.removeField('email');
AccountsTemplates.addFields([
  {
    _id: "username",
    type: "text",
    displayName: "username",
    required: true,
    func: function(value){
      if (Meteor.isClient) {
        console.log("Validating username...");
        var self = this;
        Meteor.call("userExists", value, function(err, userExists){
          if (!userExists)
            self.setSuccess();
          else
            self.setError(userExists);
          self.setValidating(false);
        });
        return;
      }
      // Server
      return Meteor.call("userExists", value);
    },
    minLength: 5,
  },
  {
    _id: 'email',
    type: 'email',
    required: true,
    displayName: "email",
    re: /.+@(.+){2,}\.(.+){2,}/,
    errStr: 'Invalid email',
  },
  pwd
]);

https://github.com/meteor-useraccounts/core/blob/master/Guide.md

#2


You need to use .s to access properties of objects, not spaces

您需要使用.s来访问对象的属性,而不是空格

Meteor.users.findOne

#3


You provided very little information to spot your problem. This said, how are you letting your users in?

您提供的信息很少,无法发现您的问题。这就是说,你如何让你的用户进入?

Be aware that OAuth registrations do not provide a username field on the created user object, as well as password registration based on email address only. In these cases user.username would be undefined.

请注意,OAuth注册不会在创建的用户对象上提供用户名字段,也不会仅基于电子邮件地址提供密码注册。在这些情况下,user.username将是未定义的。

I'd suggest to make sure all your users get a profile.username (possibly exploiting some Accounts.onLogin hook or some profile page where to force the user to select a username.

我建议确保所有用户都获得profile.username(可能利用一些Accounts.onLogin挂钩或一些配置文件页面强制用户选择用户名。

After this you would extend your post metadata setting author: user.profile.username

在此之后,您将扩展您的帖子元数据设置作者:user.profile.username

#1


From the Useraccounts doc, Try this:

从Useraccounts文档中,试试这个:

if (Meteor.isServer){
    Meteor.methods({
        "userExists": function(username){
            return !!Meteor.users.findOne({username: username});
        },
    });
}

AccountsTemplates.addField({
    _id: 'username',
    type: 'text',
    required: true,
    func: function(value){
        if (Meteor.isClient) {
            console.log("Validating username...");
            var self = this;
            Meteor.call("userExists", value, function(err, userExists){
                if (!userExists)
                    self.setSuccess();
                else
                    self.setError(userExists);
                self.setValidating(false);
            });
            return;
        }
        // Server
        return Meteor.call("userExists", value);
    },
});

This will add the username field to your login/register forms and check for username conflicts when registering new users.

这会将用户名字段添加到您的登录/注册表单中,并在注册新用户时检查用户名冲突。

The top part is server code the bottom part is common code, so you could place this whole snippet in project/lib/ folder, or place the method with the rest of your methods, depending on how your structuring your project.

顶部是服务器代码,底部是公共代码,因此您可以将整个代码段放在project / lib /文件夹中,或者将方法与其余方法放在一起,具体取决于构建项目的方式。

Use the following to have the username field show up first instead of last on the register form:

使用以下命令在注册表单中首先显示用户名字段而不是最后一个:

var pwd = AccountsTemplates.removeField('password');
AccountsTemplates.removeField('email');
AccountsTemplates.addFields([
  {
    _id: "username",
    type: "text",
    displayName: "username",
    required: true,
    func: function(value){
      if (Meteor.isClient) {
        console.log("Validating username...");
        var self = this;
        Meteor.call("userExists", value, function(err, userExists){
          if (!userExists)
            self.setSuccess();
          else
            self.setError(userExists);
          self.setValidating(false);
        });
        return;
      }
      // Server
      return Meteor.call("userExists", value);
    },
    minLength: 5,
  },
  {
    _id: 'email',
    type: 'email',
    required: true,
    displayName: "email",
    re: /.+@(.+){2,}\.(.+){2,}/,
    errStr: 'Invalid email',
  },
  pwd
]);

https://github.com/meteor-useraccounts/core/blob/master/Guide.md

#2


You need to use .s to access properties of objects, not spaces

您需要使用.s来访问对象的属性,而不是空格

Meteor.users.findOne

#3


You provided very little information to spot your problem. This said, how are you letting your users in?

您提供的信息很少,无法发现您的问题。这就是说,你如何让你的用户进入?

Be aware that OAuth registrations do not provide a username field on the created user object, as well as password registration based on email address only. In these cases user.username would be undefined.

请注意,OAuth注册不会在创建的用户对象上提供用户名字段,也不会仅基于电子邮件地址提供密码注册。在这些情况下,user.username将是未定义的。

I'd suggest to make sure all your users get a profile.username (possibly exploiting some Accounts.onLogin hook or some profile page where to force the user to select a username.

我建议确保所有用户都获得profile.username(可能利用一些Accounts.onLogin挂钩或一些配置文件页面强制用户选择用户名。

After this you would extend your post metadata setting author: user.profile.username

在此之后,您将扩展您的帖子元数据设置作者:user.profile.username