如何将对象插入到流星集合中

如何将对象插入到流星集合中

本文介绍了如何将对象插入到流星集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 Meteorjs,问题多于答案.

I am just starting to learn Meteorjs and have more questions than answers.

我想将我的应用程序的翻译存储到一个临时集合中,并订阅 Iron Router 以进行发布.我有一个我想插入到集合中的字典对象.

I want to store translations for my app into a temporary Collection, and subscribe Iron Router to its publishing. I have a dictionary-object that I want to insert into the Collection.

这是我的做法:

server/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);

server/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?
    }
});

如何在客户端使用这些对象?

How can I use these Objects client-side?

推荐答案

有一些客户端/服务器放置问题,您似乎也在解决这个问题,但让我们专注于您的问题并缩小问题的范围.

There's a few client/server placement issues it seems like you're working through here too, but let's focus on your question and narrow down the problem.

定义您的收藏

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

引导数据库数据

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'
        });
    }
}

发布

如果你发布一个带有参数的集合

If you publish a collection with an argument

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

订阅

你可以用这样的参数订阅

You can subscribe with the argument like this

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

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

For the sake of simplicity I'll leave out iron-router, since there's a few things you have to do to setup ({{yield}} in your main template and the Router.map -- Iron Router Quickstart)

模板助手

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

模板

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

这篇关于如何将对象插入到流星集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:21