Accessing MongoDB collection in Meteor without the need for a template

In my current project, I am working with a collection where I have imported data from a JSON file using the code snippet

Data.insert( JSON.parse(Assets.getText('data.json')) );
. Now, I am looking to store all this data in a variable within a separate JavaScript file that is not tied to any specific template.

Instead of simply using

var data = Data.find({}).fetch()[0]
, I have encountered issues with this approach as sometimes the fetch method returns an empty array, resulting in undefined. This leads me to believe that there might be a better way to achieve this. What would be the correct and more reliable method?

Answer №1

It seems like the data may not always be available when you make the find call (you can try using findOne instead).

Based on your comments, it sounds like you might want to place the function calling find inside a Tracker.autorun() so that the variable updates as new data is received. If this code isn't within a template helper, it won't be re-run as new data arrives from the server. If something in your template relies on it, then it may be best to include it in a helper within your template.

If the data will not change after the server has started up, you can utilize publish and subscribe mechanisms to declare your data as ready() once it's loaded on the server. You can then perform client-side processing in an onReady() callback within your subscribe() function, like this:

On the server:

Meteor.publish("startupData", function (){ 
    if (!this.userId) 
        return this.ready();
    else 
        return StartUpData.find({userId: this.userId});
}

On the client:

var startupData;
Meteor.subscribe("startupData", function(){
    var initStartupData = StartUpData.find({}) //will retrieve all published data for this user
    startupData = doPostProcessing(initStartupData)
}

Furthermore, in the case of unchanging initial data, ensure that any template dependent on the data doesn't render until the data has been received. I've managed this scenario before using IronRouter's waiton feature, such as:

Router.route('/path', {
  name: "waiting_route_name",
  waitOn: function(){
    return Meteor.subscribe('yoursub', function post_process_onready(){
        //post processing here
    });
  },
  loadingTemplate: 'loading',
  action: function(){
    this.render("the_template_name")
  }
})

That being said... If there's a template relying on specific data, it's often a sign that the data should either be provided in a helper for that template or as the data context itself. Meteor will handle re-rendering automatically as the data arrives or changes.

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

How can I incorporate a new method into the prototype of multiple objects simultaneously?

Imagine I am in possession of 100 different objects var a={name:'a'}; var b={name:'b'}; ... ... var xyz={name:'xyz'}; I am looking to incorporate a method into each object that will execute a specific action for all objects, ...

Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code: const fetcher = (url: string) => axios.get(url).then((r) => r.data); const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000}) console.log(data.find(d => d.id === "123")) The API path is ...

I require assistance with retrieving a specific element from a mongodb document and modifying its value by utilizing go mongo drivers

Greetings! I am utilizing the go.mongodb.org/mongo-driver package in golang. Here's the code snippet: package src import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/bson" "go. ...

Retrieve the ID of the Bootstrap modal element when it is hidden using the event "

I need to retrieve the ID of the modal that is currently being hidden in bootstrap. I haven't been able to figure out how to do this with the following code: $(document).on('hide.bs.modal', function (e) { // I want to know the attribu ...

Building and filling a fixed-width array in JavaScript

I have a collection of data in the following format: [[timestamp, jobid, time to completion],[..]] This data is sourced from a SQL database and is grouped by timestamp and jobid. The array looks like this: [ [1, 30, 400], [1, 31, 200], [2, 29, 300 ...

Encountering Errors when Transitioning a Standard React Component to TypeScript

I am currently in the process of migrating https://github.com/catalinmiron/react-typical to TypeScript. However, I am encountering some challenges. Below is a screenshot depicting the errors in VSCode: https://i.sstatic.net/IKZK2.png Here is the same co ...

Saving multiple nested objects within a mongoose schema

Trying my hand at creating my first REST API using Mongoose. I've been working on this for days but can't seem to make it work. I want to save a survey with an array of controls, and each control should have an array of control properties. In s ...

Ways to generate a dynamic dropdown menu with Vuejs or another versatile component

In my current project, I am facing the challenge of dynamically adding a Vue component into my template while the app is running. Although this approach may not be the typical preference for working with Vuejs, it is necessary for the requirements of my pr ...

Form submission in Ajax triggered twice

Despite using preventDefault() and return false, my Ajax form seems to be submitting twice inexplicably. <script type="text/javascript> $("#form_codes").submit(function(e) { e.preventDefault(); $.ajax({ data: $(' ...

Make changes by deleting and adding content according to the JSON data

I am currently working on updating my HTML based on a dynamic JSON script. The JSON script is constantly changing, with objects being deleted and new ones added periodically. Every 5 seconds, the script runs to check for any new objects that are not curr ...

The reason behind the issue of Too many re-renders caused by the useState react hook is due to React's limitation on the number of renders in order

In my code snippet below, I am encountering an issue: const [customers, setCustomer] = useState([]); if(users.results){ users.results.filter(user => { user.roles.filter(role => { if(role.role.name === 'ADMIN'){ ...

Using Go language, learn the steps to efficiently update the final element within an embedded array in MongoDB

I am struggling with updating a collection in my database that has the following structure: { "_id": ObjectId("..."), "rides": [ { status_history: ["status1", "status2", "st ...

How can I access a field value in a Scala class without using reflection and instead utilizing strings?

class Person { name: String, age: Int } val person = Person( name = "John", age = 30 ) Assuming we have the string "name", I need to retrieve the value of person.name, which is "John". Can this be achieved without relying on reflection, c ...

Searching for specific keys within subdocuments in PHP using MongoDB

Can anyone help me with fetching a row in Mongo by matching the subdocument in PHP Mongo? I am looking to achieve a result similar to this MySQL query: users like "14:" or invoice_id="2" Here is the structure of my data in Mongo: " ...

"Trigger a new browser tab to open with object parameters upon clicking using ng

I need to open a link in a new tab, but I am encountering an issue with sending object parameters along with it. Here is the HTML code: <a ng-click="go(row)" ></a> And here is the JavaScript code: $state.go('link', { 'searc ...

Angular styling and form error issue

Hey there! I'm new to Angular and facing a major issue along with a minor styling problem. Let's start with the big one: <mat-form-field appearance="fill"> <mat-label>Password</mat-label> <input matInput ...

Encountering an unhandled method in the VSCode JSON language server

Last week, I shared a post on my progress regarding the packages that power VSCode's JSON support through extensions. These include: https://github.com/vscode-langservers/vscode-json-languageserver https://github.com/Microsoft/vscode-json-languageser ...

Issues with refreshing Datatables functionality

I’ve hit a roadblock while troubleshooting this issue, and it’s gotten quite frustrating. That's why I've turned to Stackoverflow for help once again. As a beginner, I ask for your patience and thank you in advance for any assistance. In my ...

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

How can I navigate to a new URL using Selenium and JavaScript?

The value of the_id is currently set to 31 I am looking for a way to navigate to that specific URL using JavaScript in Selenium. Here is what I have attempted so far: store # I'm not sure which command to use here. It's not "open" as that just ...