【问题标题】:How to return number of items in collection?如何返回集合中的项目数?
【发布时间】:2015-03-25 10:01:50
【问题描述】:

我是 Meteor 的新手,我想用集合中的项目创建幻灯片,在本例中是简单的单词。幻灯片应由后退和前进按钮控制并替换当前单词。

在 JavaScript/jQuery 中,我将创建一个对象数组和一个控制索引,并通过 if 语句进行限制,因此索引永远不会低于零或溢出数组的长度。

查看小提琴的工作示例:

http://jsfiddle.net/j0pqd26w/8/

$(document).ready(function() {
var wordArray = ["hello", "yes", "no", "maybe"];
var arrayIndex = 0;

$('#word').html(wordArray[arrayIndex]);

$("#previous").click(function(){
    if (arrayIndex > 0) {
     arrayIndex -= 1;
    }
    $('#word').html(wordArray[arrayIndex]);

});

$("#next").click(function(){
    if (arrayIndex < wordArray.length) {
                arrayIndex += 1;
    }

    $('#word').html(wordArray[arrayIndex]);

  }); 
});

流星

我很好奇如何在流星的最佳实践方面实现这一点并遵守反应模式,因为我仍在尝试围绕这个有趣的框架进行思考。我的第一个障碍是翻译

if (arrayIndex < wordArray.length)
// to
if (Session.get("wordIndex") < ( (((length of collection))) )

根据文档,我应该对集合进行查找,但我只能稍后通过 fetch 返回一个空数组。对不起,如果这很长,但任何输入都可以帮助我解决这个问题。

collection.find([selector], [options])
cursor.fetch()

这是我目前的代码:

Words = new Mongo.Collection("words");

if (Meteor.isClient) {

  // word index starts at 0
  Session.setDefault("wordIndex", 0);

  Template.body.helpers({
    words: function () {
      return Words.find({});
    },
    wordIndex: function () {
      return Session.get("wordIndex");
    }
    });



    Template.body.events({
      "submit .new-word": function (event) {
        // This function is called when the word form is submitted
        var text = event.target.text.value;

        Words.insert({
          text: text,
          createdAt: new Date() //current time
        });

        // Clear form
        event.target.text.value = "";

        // Prevent default form submit
        return false;
      },
      'click #previous': function () {
        // decrement the word index when button is clicked
        if (Session.get("wordIndex") > 0) {
          Session.set("wordIndex", Session.get("wordIndex") - 1);
        }
      },
      'click #next': function () {
        // increment the word index when button is clicked
          if (Session.get("wordIndex") < 10 ) {
          Session.set("wordIndex", Session.get("wordIndex") + 1);
         }

      }

    });


}

if (Meteor.isServer) {
  Meteor.startup(function () {

  });
}

【问题讨论】:

    标签: meteor meteor-helper


    【解决方案1】:

    有一种叫做 Collection 助手的东西,它的工作方式类似于其他助手(例如,模板等)。这里有更详细的解释:https://medium.com/space-camp/meteor-doesnt-need-an-orm-2ed0edc51bc5

    【讨论】:

      【解决方案2】:

      .count() 将返回集合中的文档数。

      `db.collection.count()` 
      

      【讨论】:

        猜你喜欢
        • 2018-10-02
        • 2010-12-24
        • 2016-07-23
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 2018-12-10
        • 1970-01-01
        • 2021-08-22
        相关资源
        最近更新 更多