Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何验证Meteor.user用户名是否存在?_Meteor - Fatal编程技术网

如何验证Meteor.user用户名是否存在?

如何验证Meteor.user用户名是否存在?,meteor,Meteor,我正在构建一个messenger应用程序,在创建对话之前,我想验证是否存在用户。如果是,那么它将创建对话。如果不是,那么它应该返回一个错误。我一直在服务器端使用此代码,但由于某些原因,它无法工作。我尝试了许多不同的调整,但这基本上是我的结构: Meteor.methods({ createConversation: function(secondPerson) { function doesUserExist(secondPerson) { var userx = Me

我正在构建一个messenger应用程序,在创建对话之前,我想验证是否存在用户。如果是,那么它将创建对话。如果不是,那么它应该返回一个错误。我一直在服务器端使用此代码,但由于某些原因,它无法工作。我尝试了许多不同的调整,但这基本上是我的结构:

Meteor.methods({
createConversation: function(secondPerson) {

    function doesUserExist(secondPerson) {
        var userx = Meteor.users.findOne({username: secondPerson});
        if (userx === secondPerson) {
            return false;
        } else { 
            return true;
        }
    }

    if (doesUserExist()) { 
        Conversations.insert({
          person1: Meteor.user().username,
          person2: secondPerson
        });

    } else { 
        Conversations.insert({
          person1: "didn't work"
        });
    }



}
});

您缺少的要点是
find
返回光标,而
findOne
返回文档。以下是实现该方法的一种方法:

Meteor.methods({
createConversation:函数(用户名){
检查(用户名、字符串);
如果(!this.userId){
抛出新流星。错误(401,“您必须登录!”);
}
if(Meteor.users.findOne({username:username})){
返回对话。插入({
person1:Meteor.user()用户名,
人员2:用户名
});
}否则{
抛出新流星。错误(403,用户名+“不存在!”);
}
}
});
请注意以下功能:

  • 验证
    username
    是否为字符串
  • 要求用户登录以创建对话
  • 将用户存在性检查减少到一行
  • 返回新对话的
    id
  • 使用Meteor.Error进行解释,可以在客户端看到这些解释
要使用它,只需打开浏览器控制台并尝试拨打以下电话:

Meteor.call('createConversation', 'dweldon', function(err, id){console.log(err, id);});

您缺少的要点是
find
返回光标,而
findOne
返回文档。以下是实现该方法的一种方法:

Meteor.methods({
createConversation:函数(用户名){
检查(用户名、字符串);
如果(!this.userId){
抛出新流星。错误(401,“您必须登录!”);
}
if(Meteor.users.findOne({username:username})){
返回对话。插入({
person1:Meteor.user()用户名,
人员2:用户名
});
}否则{
抛出新流星。错误(403,用户名+“不存在!”);
}
}
});
请注意以下功能:

  • 验证
    username
    是否为字符串
  • 要求用户登录以创建对话
  • 将用户存在性检查减少到一行
  • 返回新对话的
    id
  • 使用Meteor.Error进行解释,可以在客户端看到这些解释
要使用它,只需打开浏览器控制台并尝试拨打以下电话:

Meteor.call('createConversation', 'dweldon', function(err, id){console.log(err, id);});

谢谢大卫,我明天会试一试。我刚刚也读了你的博客,很棒的材料!这对你有用吗?我很高兴你喜欢这个博客。:)这对像“Test”和“Test”或“Test”这样的用户名不起作用谢谢David,我明天会试试。我刚刚也读了你的博客,很棒的材料!这对你有用吗?我很高兴你喜欢这个博客。:)这对“Test”和“Test”或“Test”这样的用户名不起作用