如何将对象插入到meteorcollections中

我刚刚开始学习Meteorjs,有更多的问题,而不是答案。 我想将可能的应用程序的翻译存储到临时collections,并订阅铁路路由器到其发布。 我有一些字典对象,想插入到这个集合。

我做了这样的结构:

服务器/ translations.js

translations = { ru_RU: { 'value1': 'translation1', 'value2': 'translation2' }, en_US: { 'value1': 'translation1', 'value2': 'translation2' } }; 

collections/ translates.js

 Translates = new Meteor.Collection('translations'); Translates.insert(translations); 

服务器/ publications.js

 Meteor.publish('translations', function (lang) { //<-- how to pass arguments? return Translations.find({'translations': lang}); }); 

router.js

 //use iron-router Router.configure({ layoutTemplate: 'main', notFoundTemplate: 'not-found', waitOn: function () { //waiting while data received and starting router job return Meteor.subscribe('translations');//<-- how can i use this data? } }); 

没有更多的不明白。 问题是:我怎样才能在客户端使用我的翻译?

有几个客户端/服务器放置问题,你似乎也在这里工作,但让我们专注于你的问题,并缩小问题。

定义你的collections

 Translations = new Meteor.Collection('translations'); 

Bootstrap数据库数据

 if (Meteor.isServer) { if (Translations.find({}).count() === 0) { Translations.insert({ 'translation' : 'ru_RU', 'value1': 'translation1', 'value2': 'translation2' }); Translations.insert({ 'translation': 'en_US', 'value1': 'translation1', 'value2': 'translation2' }); } } 

发布

如果你用一个参数发布一个集合

 Meteor.publish('translations', function (lang) { //lang argument return Translations.find({'translation': lang}); }); 

订阅

你可以用这样的参数来订阅

 Meteor.subscribe('translations', 'ru_RU'); // pass in the other language code 

为了简单起见,我将省去铁路路由器,因为在主模板和Router.map – 铁路路由器快速入门中需要做一些设置({{yield}),

模板助手

 Template.myTemplate.helpers({ translations: function() { // return all subscribed translations return Translations.findOne({}); } }); 

模板

 <template name='myTemplate'> {{translations.value1}}<br> {{translations.value2}} </template> 

这里有两个核心要点:

  1. Translates集合也存在于客户端。
  2. 订阅源使得由其发布的所有文档在客户端上可用:不pipe它们属于哪个集合。 你甚至可以返回一个游标数组来发布多个集合。

除此之外,你的查询和数据模型还有一些问题。

随着translationsvariables的定义,查询Translations.find({'translations': lang}); 不会find任何东西,因为它会尝试查找字段translation等于传递的对象的文档。 这可能不是你想要的。

我会build议让你的translationvariables保存以下数据:

 translations = [ { 'translation' : 'ru_RU', 'value1': 'translation1', 'value2': 'translation2' }, { 'translation': 'en_US', 'value1': 'translation1', 'value2': 'translation2' } ]; 

那么你的查询很可能会返回你想要的。

另一个build议是Translates.insert(translations); 每次服务器运行时都要将一个对象input到表中。 这也可能不是你想要的(也许你没有在实际的客户端上这样做)。 解决这个问题的方法是检查收集是否在开始时是空的:

 if (Translation.find({}).count() === 0) Translation.insert(translations); 

最后,在订阅的时候,你可以把variables传递给subscribe函数:

 waitOn: function () { return Meteor.subscribe('translations', /* user preference here */ this.params.userLanguagePreference ); } 

最后,要访问客户端上的集合,只需使用Translation.find({}) ,您将得到一个游标,该游标将遍历为您的客户订阅而发布的所有文档。