我工作的一个流星的项目,我必须说,这是不容易的没有更多的回调,尤其是对一两件事:回调!流星 - 为“findOne”功能
一切都是异步的,所以我想知道我必须怎么做才能从我的mongodb中获得结果。
var user = Meteor.users.findOne({username: "john"});
return (user); // sometimes returns "undefined"
...
var user = Meteor.users.findOne({username: "john"});
if (user) // so ok, I check if it exists!
return (user); // Cool, I got my user!
return(); // Ok and what should I return here? I want my user!
我不想脏了,把喜欢的setTimeout无处不在。 有人有这个解决方案吗?
编辑: 我router.js发现与我的数据返回4倍的console.log。 2次使用未定义的值,另外2次使用期望值。在视图中,它仍然是未定义的。 为什么路由器在这条路由中经过了4次?它是否显示路由器中返回值的第一个结果?
如果find()找不到任何东西,我应该返回什么?
编辑2:下面是一些代码来理解。
this.route('profilePage', {
path: 'profil/:_id?',
waitOn: function() {
return [
Meteor.subscribe('article', { prop: this.params._id}), // id can be id or username
Meteor.subscribe('article', { userId: this.params._id}), // id can be id or username
Meteor.subscribe('params'),
Meteor.subscribe('profil', (this.params._id ? this.params._id : Meteor.userId()))
];
},
data: function() {
if (this.params._id) {
var user = Meteor.users.findOne(this.params._id);
if (!user)
user = Meteor.users.findOne({username: this.params._id});
console.log(user);
return user;
}
else if (Meteor.userId())
return Meteor.user();
else
Router.go("userCreate");
}
});
我得到这个在控制台上: http://puu.sh/debdJ/69419911f7.png
(以下文字版)
undefined
undefined
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
我相当肯定'findOne'不是异步的,你的第一个例子应该没问题。我假设你在客户端上这样做,你想确保你正在寻找的用户在你的客户端集合中。在你的浏览器控制台中运行'Meteor.users.findOne({username:“john”})',这应该是同步出来的问题。 – Shaded 2014-12-01 19:41:21
findOne应该是同步的和被动的。你是说有时它返回undefined,即使查询应该返回一个值?请注意,我通常只使用findOne和_id,这可能是我体验不同行为的部分原因。 – 2014-12-01 19:42:06
@LarryMaccherone是的,就是这样。它返回undefined,它应该返回别的东西。我注意到console.log中的数据在routes.js中返回4次:2次使用undefined,2次使用期望的对象。但在视图中,该对象是未定义的。 – Sw0ut 2014-12-01 20:03:34