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

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

我想在页面加载后尽快执行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({})); }); }

但是,这不起作用(它显示"undefined").从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.

推荐答案

您应首先publish来自服务器的数据.

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.

更多推荐

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

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

发布评论

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

>www.elefans.com

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