Using Meteor package to efficiently import JSON arrays into mongoDB

I am currently working on developing a meteor package that will allow users to import JSON files into collections in a mongoDB. However, I'm uncertain about the feasibility of this task.

The idea is for the user to upload a JSON file and specify the collection name in an input field for the import process. Subsequently, the JSON array should be stored in the specified collection.

HTML:

<template name="importJSON">
    <form id="importJson">
        <input type="text" id="collection">
        <input type="file" id="file">
    </form>
</template>

Meteor:

Template.importJSON.events({
    'submit #importJson': function(e){
        e.preventDefault();
        var collection = e.target.collection.value;
        var obj = JSON.parse(response);
        db.collection.insert(obj);
    }
});

However, I am faced with three challenges:

1) How do I handle the actual file upload process, especially since the file needs to be uploaded temporarily?

2) Is there a way to dynamically use the inputted collection name?

3) How can I ensure that the imported data is inserted correctly? Using insert might simply append the new data to existing data, correct?

Answer №1

To address the three questions you mentioned:

1) What is the best way to handle temporary file uploads?

If your goal is simply to read the file and insert it into a collection, you can achieve this without actually uploading the file. You can read the file on the client-side. Here is a helpful article on Reading files in JavaScript using the File APIs.

2) How do I use the input-field provided collection name?

Let's assume the collection name provided in the input field is products. If you have sample data structured like this:

{
  "name": "Product",
  "id": "Product identifier",
  "name": "Name of the product",
  "price": "9990",
  "tags": ["tag1", "tag2"]
}

You would first need to have a corresponding collection on the server side.

<your app name>/lib/collections/products.js

Products = new Meteor.Collection('Products');

In your client-side code:

var rawproducts = (content of the file you read using the File API)
var newproducts = JSON.parse(rawproducts);

for (var i = 0; i < newproducts.length; i++) {
  Products.insert(newproducts[i]);
}

You can also test this locally by creating a local-only collection.

//pass null as collection name, it will create
//local only collection
Products = new Mongo.Collection(null);

for (var i = 0; i < newproducts.length; i++) {
 Products.insert(newproducts[i]);
}

Note: Using a local-only collection means the data remains on the client side.

3) How should I import data correctly without just appending it?

The method described above for importing data will keep appending the new data. Consider implementing a mechanism to de-dupe or completely replace existing data if necessary.

Hope this clarifies things.


Update:

How can I remove all elements from a collection?

Products.remove({}) // removes every product

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

Work with Dart Language to Parse a Nested JSON Array and Store it in a Model Class

In regards to my inquiry here I am seeking a solution to extract and parse a JSON array without a key nested within another JSON array, and then store it in a Model class. Below is the JSON Array that requires parsing: [ { "pk": 100, ...

Obtaining JSON data using Jquery results in the output of "undefined"

I am struggling to extract the correct values from a JSON document in order to display schedules in list view. Currently, when accessing the JSON document, I keep receiving "undefined" as the result. Below is an example of the JSON document: { "Ferries": ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

Encountering a build error in Next.js 13 when attempting to fetch an API route within a server component

I encountered an issue while building my next app (yarn run build). To troubleshoot, I created a new clean project and tested it. The problem seems to be with my route (/api/categories/route.ts) export async function GET() { return new Response(JSON.str ...

What methods should I use to modify the upcoming array of objects?

I have been struggling with this exercise for about an hour now, and I can't figure it out. Can someone please help me with this? Here is the array that I retrieved from the database: View Base Array Image let data = [ { "name": "October : 2019", "u ...

When XMLHttprequest is used to send a POST request, it sometimes

Here is the code I'm using to send a request: let ajaxHandler = new XMLHttpRequest(); ajaxHandler.onreadystatechange = function() { if(ajaxHandler.readyState == 4) { console.log(ajaxHandler.responseText); } } ajaxHandler.open("POST", ...

Having trouble parsing Json using the Map interface and the ObjectMapper

Lately, I've been diving into Json parsing but haven't had much practice with collections yet. I have a Json String: { "time":1352113682, "api_version":"1", "firstname":"abc", "lastname":"xyz", "company":"Cool Apps", " ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Unlimited Cycle using Vue Router Global Precautionary Measures

Currently, I am facing an issue with redirecting users using Firebase Auth and Vue Router. The problem arises when the Router redirects the user to '/' as it results in a blank white screen on the website. I am aware that there is an error in m ...

Tips for determining if a user is refreshing the page or navigating to a different page

Scenario: I need to store a specific variable in the local storage every time a user exits the page. By utilizing the window.onbeforeunload method, I am able to capture the event when a user is leaving the page. However, I want to assign different values ...

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

What is the process to retrieve a function from a router javascript file using node.js?

Dealing with a web application that is not my own, I now have the task of sending out one hundred emails. Unfortunately, the code is poorly documented and written, which means I need to test it to figure out what I can and cannot do. However, I'm uns ...

The specified message formats required for the operation include 'XML' and 'JSON'

Creating a WCF REST service includes defining methods for adding, deleting, and editing news entities. Here is an example of such a service: [ServiceContract] public interface INewsRepository { [OperationContract] [WebInvoke(Me ...

jQuery functions failing to target dynamically generated elements

I've encountered an issue while attempting to implement my jQuery functions on dynamically created content using the .on API from jQuery. The main objective of the code is to display a specific set of options only when a user hovers over the ".feed_po ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

Troubleshooting Rails 4: Handling a 404 Not Found Error When Making an AJAX Call to a

After spending about an hour trying to figure this out, I am still stuck... The action in my oferts_controller.rb file looks like this: def update_categories @categories = Category.children_of(Category.find(params[:categories])) respond_to ...

Tips for enabling resize functionality on individual components one at a time

Check out my Codepen link for the resizable event While using Jquery UI resizable, everything is functioning correctly. However, I am now looking to have the resizable event activate one block at a time. When another block is clicked, the resizable event ...

(node:32032) UnhandledPromiseRejectionWarning: Promise rejected without handling it (rejection id: 1): MongoDB Error: Unable to authenticate

I attempted to establish a connection with MongoDB through mLab. I inputted the code below: Mongoose.connect('mongodb://<dhan004>:<password1>@ds163402.mlab.com:63402/projecttwist', {useNewUrlParser: true }); However, an error was r ...

can you explain which documents outline the parameters that are passed into the express app.METHOD callback function?

As a beginner in javascript and nodejs, I often struggle with understanding callback functions. One thing that particularly confuses me is determining what arguments are passed into a callback function. Let's consider the following example: app.get( ...

Retrieving specific embedded documents in MongoDB using Ruby and Mongoid

I have a collection of users, with each user containing an array of embedded support request documents. class User < MyModel include Mongoid::Document embeds_many :tickets ... end class Ticket < MyModel include Mongoid::Document embedded_ ...