我是Meteor的新手,并试图找出如何检查用户是否已存在于数据库中。用户名是通过表单提交的,我希望代码在继续下面的代码之前等待回复。
我以为我已经想通了,但即使我知道用户已经存在于数据库中,我也收到了未定义的回复。
这是我到目前为止所拥有的:
在浏览器控制台中,这会成功执行。
Meteor.users.findOne({'$or': [{'username': 'me@example.com'},{'emails.address': 'me@example.com'}]});
在Mongo终端控制台中,这会成功执行。
db.users.findOne({'$or': [{'username': 'me@example.com'},{'emails.address': 'me@example.com'}]});
example.js:
if (Meteor.isClient) {
// This code only runs on the client
Meteor.subscribe("users");
Template.registration.events({
"submit #register_form": function (event) {
// This function is called when the registration form is submitted.
var form_data = {
username: event.target.username.value,
email: event.target.email.value,
password: event.target.password.value,
first_name: event.target.first_name.value,
last_name: event.target.last_name.value,
website: event.target.website.value
};
// Sync call. Wait for reply before executing remaining code below.
var result = Meteor.call("check_username", form_data.username);
alert("result = " + result); // Returns undefined.
// Execute remaining code if user does not exist.
}
});
}
Meteor.methods({
check_username: function (username) {
// Check if user exists.
var user = Meteor.users.findOne({
'$or': [
{'username': username},
{'emails.address': username}
]
});
return user;
// Should I do this instead?
//if (!user) {
// throw new Meteor.Error("user exists", "That user already exists.");
//}
}
});
if (Meteor.isServer) {
Meteor.publish("users", function () {
return Meteor.users.find();
});
}
答案 0 :(得分:3)
这是预期的行为,请看一下我的详细答案:
Meteor.methods returns undefined
您需要做的是使用Meteor.call
的异步语法在实际从服务器返回结果时执行任意代码。
Meteor.call("check_username", form_data.username,function(error, result){
if(error){
console.log(error.reason);
return;
}
alert("result = " + result); // Returns the result computed on the server
if(!result){
// Execute remaining code if user does not exist.
}
});