gpt4 book ai didi

meteor - 如何返回集合中的项目数?

转载 作者:行者123 更新时间:2023-12-01 11:34:53 25 4
gpt4 key购买 nike

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

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

工作示例参见 fiddle :

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]);

});
});

meteor

我很好奇如何在 meteor 的最佳实践中实现这一点并遵守 react 模式,因为我仍在努力思考这个有趣的框架。我的第一个障碍是翻译

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 () {

});
}

最佳答案

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

`db.collection.count()` 

关于meteor - 如何返回集合中的项目数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28159471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com