Meteor:我怎么知道数据库什么时候准备好?

编程入门 行业动态 更新时间:2024-10-11 09:22:19
本文介绍了Meteor:我怎么知道数据库什么时候准备好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在页面加载后尽快执行 Meteor 集合查询.我尝试的第一件事是这样的:

I want to perform a Meteor collection query as soon as possible after page-load. The first thing I tried was something like this:

Games = new Meteor.Collection("games"); if (Meteor.isClient) { Meteor.startup(function() { console.log(Games.findOne({})); }); }

但这不起作用(它打印未定义").当从 JavaScript 控制台调用时,相同的查询会在几秒钟后生效.我认为在数据库准备好之前存在某种滞后.那么我怎么知道这个查询什么时候会成功呢?

This doesn't work, though (it prints "undefined"). The same query works a few seconds later when invoked from the JavaScript console. I assume there's some kind of lag before the database is ready. So how can I tell when this query will succeed?

OSX 10.8 和 Chrome 25 下的流星版本 0.5.7 (7b1bf062b9).

Meteor version 0.5.7 (7b1bf062b9) under OSX 10.8 and Chrome 25.

推荐答案

您应该首先发布来自服务器的数据.

You should first publish the data from the server.

if(Meteor.isServer) { Meteor.publish('default_db_data', function(){ return Games.find({}); }); }

在客户端,只有在从服务器加载数据后才执行集合查询.这可以通过在 subscribe 调用中使用反应式会话来完成.

On the client, perform the collection queries only after the data have been loaded from the server. This can be done by using a reactive session inside the subscribe calls.

if (Meteor.isClient) { Meteor.startup(function() { Session.set('data_loaded', false); }); Meteor.subscribe('default_db_data', function(){ //Set the reactive session as true to indicate that the data have been loaded Session.set('data_loaded', true); }); }

现在,当您执行集合查询时,您可以检查数据是否已加载:

Now when you perform collection queries, you can check if the data is loaded or not as:

if(Session.get('data_loaded')){ Games.find({}); }

注意:删除 autopublish 包,它默认将您的所有数据发布到客户端,这是不好的做法.

Note: Remove autopublish package, it publishes all your data by default to the client and is poor practice.

要删除它,请从根项目目录对每个项目执行 $meteor remove autopublish.

To remove it, execute $ meteor remove autopublish on every project from the root project directory.

更多推荐

Meteor:我怎么知道数据库什么时候准备好?

本文发布于:2023-11-10 14:24:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575614.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   数据库   我怎么   Meteor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!