Import JSON data into a Meteor collection

Currently, I am faced with the task of importing a JSON file containing embedded objects into MongoDB. I need to ensure that the document format remains unchanged during the import process. My main challenge lies in creating or modifying a function/method that will allow me to import the file while associating the _id within the sport-events array loop (in this case, simplified to just one sports-event array for brevity).

To rephrase my question: How can I import only the data within the sports-event array without altering the rest of the document structure?

JSON Document:

{
"sports-content": {
    "sport-event": [{
        "event-metadata": {
            "league": "NCAA Basketball",
            "event-type": "0",
            "league-details": "NCAAB",
            "event-date-time": "12/18/2015 07:00 PM",
            "eventNum": "3000460",
            "status": "",
            "off-the-board": "False"
        },
        "team": [{
            "team-metadata": {
                "alignment": "Home",
                "nss": "526",
                "openNum": "526",
                "name": {
                    "full": "Clemson"
                }
            },
            "wagering-stats": {
                "wagering-straight-spread": {
                    "bookmaker-name": "BetOnline",
                    "active": "true",
                    "line": "1.5",
                    "money": "-110",
                    "context": "current"
                }
            },
            "team-stats": {
                "score": "0"
            }
        }, {
            "team-metadata": {
                "alignment": "Away",
                "openNum": "525",
                "nss": "525",
                "name": {
                    "full": "South Carolina"
                }
            },
            "wagering-stats": {
                "wagering-straight-spread": {
                    "bookmaker-name": "BetOnline",
                    "active": "true",
                    "line": "-1.5",
                    "money": "-110",
                    "context": "current"
                }
            },
            "team-stats": {
                "score": "0"
            }
        }]
    }],
    "sports-meta-data": {
        "doc-time": "42353.5979256944"
    }
  }
 }

Inside Meteor server.js wrapped in Meteor.startup:

if (SportEventsFeed.find().count() === 0) {
    console.log("Importing private/products.json to db")

    var data = JSON.parse(Assets.getText("ncaab.json"));

    data.forEach(function (item, index, array) {
        SportEventsFeed.insert(item);
    })
}

Answer №1

To easily add the items from the 'sports-event' array as separate documents in the database, follow these steps:
If you prefer a different value for the _id field, feel free to modify the item_id variable.

if (SportEventsFeed.find().count() === 0) {
  console.log("Importing private/products.json to db")

  var data = JSON.parse(Assets.getText("ncaab.json"));

  data['sports-content']['sports-event'].forEach(function (item, index, array) {
    item._id = index;
    SportEventsFeed.insert(item);
  })
}

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

Switch out the "Wishlist" button for the "Add to Cart

While managing my Opencart store, I encountered a requirement to replace the "Add to Wishlist" button with an "Add to Cart" button on the product page. After making changes to the code, the appearance of the button was successfully updated. CODE ...

Downloading files from a Blob in NodeJS: A step-by-step guide

How do I retrieve a file from a BLOB column using NodeJS? Currently, I am utilizing the oracledb library for database operations and my code snippet is as follows: async function getFile(req, res) { let filename = req.params.filename; let file = a ...

Transform an array of JSON data into a structured dataframe

I am looking to transform the owid Covid-19 JSON data found here into a dataframe. This JSON contains daily records in the data column, and I aim to merge this with the country index to create the desired dataframe. {"AFG":{"continent": ...

My npm init script is failing to work properly. What steps can I take to troubleshoot

I am encountering an issue while setting up a new node.js project and attempting to generate the package.json file. As a Windows user, I am utilizing Visual Studio Code terminal for my project setup. However, when I enter the command npm init, I am faced w ...

It is not possible for Jquery to encode JSON data

After retrieving this JSON data from my PHP page, jQuery seems to have trouble decoding it as the result is always null. { "City": [ { "CityID": "1", "CityName": "istanbul" }, { "CityID": "2" ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Determining if a method's timeout has been triggered while running on a periodic basis in JavaScript

Within my JavaScript code, I have implemented a method that runs every 5 minutes. However, after 15 minutes, I want to stop this method from executing. var tChk ; tChk = setInterval("test()", 5*60*1000); setTimeout("timeOut(tChk)", 15*60*1000); // 15 mins ...

MongoDB offers a versatile approach to managing data structures

As I dive into learning Mongo DB for the first time, I've decided to use it for my current project due to its ability to accommodate a flexible schema based on user inputs. In mySql, I previously had a table dedicated to storing user-entered data tha ...

Encountering problems with Spring Native while establishing a connection to MongoDB

In my spring application, I am utilizing mongodb for persistence. The connection to mongodb requires a username and password. Recently, I decided to explore the benefits of using Spring Native and created a docker image on my Ubuntu 18 LTS environment. Af ...

Unraveling dependencies in deno for debugging purposes

When working with Node + NPM, dependencies are installed in node_modules, making it easy to debug by adding debugger statements or console logs directly in the node_modules/some-pkg/some-file.js. In Deno, things are a bit more complex as dependencies are ...

Error encountered while trying to access the user information from Firestore/Firebase

When I attempt to display the current user that is logged in console.log(firebase.auth().currentUser.uid) The user's UID is outputted. I then decided to retrieve the current user's information from Firestore using the following code: import ...

Rotating items to reset their y-angle in Three.js

In my three.js game project, I am developing cars that move in different directions based on their y-rotation angle. For instance, a rotation of 90 degrees. To move them forward, I use the object.translateZ() method, but I am facing an issue. Utilizing ph ...

What is the reason behind TypeScript allowing arguments to be passed in the incorrect order?

Why doesn't TypeScript throw an error when the arguments are passed in the wrong order with these simple wrapper Types? class FirstName { constructor(public value: string) {} } class LastName { constructor(public value: string) {} } function ...

Tips for patiently anticipating an object to undergo asynchronous modifications?

I have an array containing items, and I need to incorporate the asynchronous value from getProductMinQuantity. The issue I'm facing is that the response with res.status(200)... gets sent before modifying item.order_quantity_minimum. I had assumed us ...

The latest pathway fails to refresh in NextJs

I've implemented a search bar at the top of my app which directs to /search/[searchId].js page: <Link href={`/search/${search}`}> <button type='submit' className='btn-cta btn-3'>SEARCH</button> < ...

Obtain a JSON object from a template view that is iterable and does not contain any Unicode values

I have structured a dictionary in Python (2.7) like this: cntr_rgns = {'country_1':[region1, region2, region3], 'country_2':[region1, region2] ..} Then I pass it to my context dictionary as: ctx['regions'] = cntr_rgns The ...

What is the syntax for implementing a for loop/for each loop in EJS?

I'm trying to figure out how to include this code snippet inside <% %>. I'm not sure if it's similar to a typical forEach/for loop. The documentation on EJS site is quite limited, so I've turned to this forum for help. <% incl ...

Combining a string with a number in a loop using JavaScript and AngularJS

var number = 0; var date = "2016-05-10" $scope.test = date; I am trying to create a loop using the variable number in order to achieve the following result: $scope.test1 = 2016-05-10 $scope.test2 = 2016-05-10 $scope.test3 = 2016-05-10 The $scope.test ...

Guide to utilizing an npm package binary without going through the installation process

My goal is to develop a CLI tool (using Node and NPM) that can create an application using Brunch. The intended procedure is for users to install my tool with the following command: npm install -g my-cli-tool After installation, they can create a new Br ...

Trouble activating Bootstrap 4 checkbox through JavaScript integration

When clicking on a table row, I am able to add the class active with JavaScript. However, when trying to click on a checkbox, an error occurs. Check out the live Codepen link here Below is the custom code snippet: $('.dashboard-table-tbody tr&apo ...