Techniques for extracting batches of n records from a database cursor (collection)

I am on a quest to showcase groups of 3 documents from my "Questions" collection, which contains about 50 documents. The plan is to display the first set of 3 questions in the template and then provide the users with an option (by clicking a button) to either fetch the next group of 3 documents or wrap up.

So far, I've hit a roadblock in loading the questions in batches of 3. Here's how my code looks:

collections.js:

Questions = new Mongo.Collection("questions");

myapp.js:

var lastQ=0
Template.questions.helpers ({
  getGroupQuestions: function(){
    //My goal here is to query the entire collection just once and store it in a local variable
    var listOfQuest = Questions.find({$and: [ {qNumber: {$nin: answeredQ}}, {qNumber:{$gt:lastQ}}]}, {sort:{qNumber:1}}); 

    lastQ = lastQ + 3;
    return {"Obj1":listOfQuest.fetch()[0], "Obj2":listOfQuest.fetch()[1], "Obj3":listOfQuest.fetch()[2]};  //Unfortunately, this doesn't seem to work as expected as the returned object cannot be read in the template
  }
});

myapp.html:

<template name="questions">
  <h4> Tell us a little about yourself: </h4>
  <form class="js-add-answers" id="add-answers">
    {{#each getGroupQuestions}}
      <label for="{{qNumber}}">{{qDescription}}</label>
      <input type="text" class="form-control" id="{{qNumber}}" placeholder="{{qHints}}"/>
      <p></p>
    {{/each}}
    <button class="btn btn-warning js-join-event">Save and Join</button>
    <button class="btn btn-warning js-load-more">Save and load more Q</button>        
   </form> 
</template>

Answer №1

It seems like all you need to do is incorporate the skip and limit functions in your document retrieval process. It's recommended to eliminate the "insecure" and "auto-publish" packages and implement the PUB/SUB technique in your code for enhanced security.

Below is a sample code snippet that can help you achieve the desired outcome:

You should publish the code on the server end with a specified skip count.

PROJECT/server/publish.js

Meteor.publish('getGroupQuestions', function(skipcount){
    return Questions.find(
                          {$and: [ {qNumber : {$nin: answeredQ}},
                                   {sort : {qNumber:1}}
                          },{limit : 3, skip : skipCount}
         });
});

On the client side, declare the following code as a session variable to skip the desired number of records by 3:

client/template/myapp.js

 Session.setDefault('skip', 0);
 Deps.autorun(function(){
     Meteor.subscribe('getGroupQuestions', Session.get('skip'));
 });

 Template.questions.events ({
    "submit .load-more" : function() {
        Session.set(Session.get('skip') + 3)
    }
 });

In myapp.html, make a slight modification and name the button accordingly:

client/template/myapp.html

<button name="load-more" class="btn btn-warning js-load-more">Save and load more Q</button>

Explaining the Process


  1. Initially, when the page loads, it will display the top 3 results based on the logic provided.
  2. When the user clicks the "load more" button, the template event is triggered, updating the session variable "skip" with a new value (incremented by 3).
  3. Thanks to Meteor's reactivity and asynchronous nature, the publishing container automatically refreshes the collection with the next set of 3 questions by executing the same query but with an updated skip counter from the session. This occurs seamlessly without requiring a page reload, showcasing the new group of questions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

Handling errors in chained promises and routes in Node.js/ExpressJS

I'm currently dealing with some confusion regarding how to handle errors when making function calls. To demonstrate this, I'll be using sequelizeJS as an example. Usually: First.Ctrl var second_ctrl = require( '../ctrl/second'); testC ...

Deleting MongoDB fields based on their names

In my dataset, I have demographic information categorized by zip code. Each age group is represented in 6 columns: Total; Estimate; AGE # - # Total; Margin of Error; AGE # - # Male; Estimate; AGE # - # Male; Margin of Error; AGE # - # Female; Estimate; A ...

Error in Meteor when attempting to eliminate embedded object from an array

After searching extensively on StackOverflow and Meteor forums, I still can't figure out why $pull is not working for me to remove embedded documents in MongoDB/Meteor. I've been grappling with this issue for days. Here's an example of the ...

What is the best method for extracting embedded documents from a MongoDb database?

I'm facing an issue with a dictionary of embedded documents and I need to remove all embedded documents from the dictionary where the key is not abc. The mongo script I have been using successfully is as follows: db.getCollection("users").update( ...

My Spring Boot application is functioning perfectly on IntelliJ IDEA, but experiencing issues when run on the terminal

While the Spring Boot Application runs smoothly on IntelliJ IDEA, encountering no issues, running the same jar file on the terminal results in the following error: ConfigServletWebServerApplicationContext : Exception encountered during context initial ...

What is the best way to retrieve a MongoDB document with specified fields in lowercase format?

I'm currently utilizing the PHP Mongo extension. In my MongoDB database, I have a collection of two-level documents, with each document containing an "email" field within the second level (i.e., "user_data.email" field). My goal is to retrieve a Mong ...

Obtaining the value and other attributes of a select option in Vue.js 2

I have implemented vuejs in my project and encountered a situation where I need to work with a select element containing multiple options. Here is an example of the code: <select v-model='line.unit' name='unit[]' required @change=& ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

Converting a JavaScript string into an array or dictionary

Is there a way to transform the following string: "{u'value': {u'username': u'testeuser', u'status': 1, u'firstName': u'a', u'lastName': u'a', u'gender': u'a&a ...

Troubleshooting the issue: "Error - 'Missing "data" payload in the request' when using Vue.js with Strapi"

When attempting to create a new entry in strapi by sending a post request in vue.js, I encountered the following error: message: Missing "data" payload in the request P.S: I also need to be able to upload files. I have read that using formData is ...

Can you guide me on choosing a specific field in mongodb?

For some reason, I'm having trouble calling a simple solution. I attempted to query it and then call user.connected_accounts.facebook, but that method is not working for me. I need to retrieve the number from it. Below is the code snippet: "connecte ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

Learning React: Error - Unable to access the 'data' property when it is null

Currently, I am learning React by following a tutorial available at this link: http://facebook.github.io/react/docs/tutorial.html Specifically, I am focusing on the section related to fetching data from the server, which can be found here: http://facebook ...

Using Three.js to rotate a camera-followed sphere in the scene

Currently, I'm developing a Three.js scene with a toy concept where I aim to track a sphere using a camera [demo]. However, I am facing an issue wherein I can't seem to get the sphere to "roll" without causing the camera to also rotate along with ...

What is the process for sending a post request in the inline editor of Dialogflow?

Currently, I am utilizing the blaze tier, so there should be no billing concerns. I have also added "request" : "*" in my package.json dependencies. Check out my code index.js below: ` 'use strict'; var global_request = require('requ ...

Troubleshooting tip for Angular 2: Issue with accessing object properties using dot notation

When it comes to Angular, there are two methods for accessing object values: 1. Access the property of the object using dot notation (obj.property). 2. Access the property of the object by passing in a key value pair, for example obj["property"]. If I d ...

Using Cytoscape.js to showcase Java-generated nodes

I am exploring how to generate a graph using data produced on the server side of my Java EE application. Specifically, I am wondering about the process of inserting a data structure (JSONObject) into the "elements" section in the code snippet below: $(fun ...

Issues arise with tabbed content as default content fails to display and classes are not added upon clicking

I'm currently working on a tabbed module that consists of three tabs. Here's how it operates: When the user clicks on a carousel_element, it reveals carousel_hidden-text within that div and displays it in another div called carousel_quote. I&ap ...