Is there a way to retrieve a file from a URL and sequentially add its contents to MongoDB?

On the server, I have a text file that needs to be fetched and each line from the file should be inserted as a new document in MongoDB.

For instance, if my text file located at URL "http://example.com/sample.txt" contains:

sample.txt

 abcdefg
 hijklmn
 opqrstu
 vwxyz

I aim to insert "abcdefg" as one entry in my collection, and the subsequent lines in a similar manner. The desired structure of my database is:

db.test.find().pretty()
  {"_id":sdjcvajsvjhdb36,"name":"abcdefg"},
  {"_id":chvbjedfve6f7v,"name":"hijklmn"}
  {"_id":tuhgiy837842,"name":"opqrstu"}
  {"_id":chw67t8533fif3,"name":"vwxyz"}

My current code retrieves the content of the file, adds "\n" between the lines, and inserts them as a single entry in the database.

    var file="http://example.com/sample.txt"
    var result=HTTP.call('GET',file, { auth:"test:test"});
    console.log(result.content);
    productImage.insert({"image":result.content});

The resulting entry in the collection would be:

{ "_id" : "cqcgPTEb62ay8L7Gq", "name" : "abcdefg\nhijklmn\nopqrstu\nuvwxyz" }

This code snippet is implemented within /meteorApp/server/method.js. Is there a way to achieve this goal differently? Can we directly query the MongoDB database and insert in the specified format?

Answer №1

Based on your input,

result.content has the following data:

"abcdefg\nhijklmn\nopqrstu\nuvwxyz"

Resolution:

  1. Divide the string by "\n"
  2. Insert each element into the database.

.

    var fileArray = result.content.split("\n"); // ["abcdefg","hijklmn","opqrstu","uvwxyz"] 

    fileArray.pop(); // remove the last "" item

    fileArray.forEach(function(element){
         productImage.insert({"image":element});
    });

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

After submitting a form, the Thymeleaf text vanishes from buttons and drop-down menus

Upon clicking submit, a strange issue arises - the text on buttons and drop-down items in the nav-bar disappears after the form is submitted. Despite this, the functionality still remains intact, leaving me puzzled about how to resolve this perplexing bug. ...

Migrating from jQuery to Vue: Resolving Uncaught TypeError - n.getClientRects is not a valid function

How do I convert this jquery code into Vue.js format? // Scale the cell item. $(document).on('click','.cell-item a', function(event) { event.preventDefault() var $this = $(this) console.log($this) // [a] - correct v ...

React's load event appears to be malfunctioning. What is the best way to create a page loader?

My goal is to create a page loader, so I have developed a `Loader` component that is supposed to add a load event listener on the `window`. However, it doesn't seem to be working as expected: import React, {useEffect} from "react" import &ap ...

Updating the logic for reconnection when the connection is closed in MySql's X DevAPI can be achieved by utilizing the @mysql/xdevapi module

I am currently utilizing the X DevAPI of MySql v8.0.33 with the @mysql/xdevapi v8.0.33 package. Although I have implemented a reconnect logic, it doesn't seem to be functioning as expected. Here is the code snippet: const mysqlx = require('@mysq ...

Setting a CSS Variable with the Help of jQuery

I need help with changing the background color of a specific .div element when it is clicked on. I want the color to be a variable that can be changed by the user, and this change should occur when the document is ready. Currently, I am using a CSS variab ...

JavaScript Object has Not Been Defined

Currently, I am developing a small program for myself related to a video game. The main issue I am facing is that certain objects are being flagged as not defined when the errors appear on the page. $(document).ready(function(){ //A list of chara ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Looking to execute a PHP file from HTML/JavaScript?

Greetings! I have a unique jQuery/javascript plugin that functions as a vertical ticker for news updates directly on my HTML website. Here is the code snippet: <script src="jquery.vticker-min.js"></script> <script type="text/ja ...

What is the best way to sort through the items in a dropdown menu?

Can you help me with a scenario where I need to filter elements in a dropdown based on input given in a text box? I have tried using ng-change but it doesn't seem to work. Is there another way to achieve this? Here is the HTML code snippet: <inpu ...

Issue with modal not being able to close the embedded video iframe

I have created a demo of a video in my footer that uses external CSS files and works perfectly. However, when I added it to the project, everything works except for closing the video. After clicking the play button in the footer, a modal appears on the sc ...

What are the best practices for implementing DBCursor from the mongodb java driver in spring-data-mongodb?

I am seeking the best approach to retrieve around 1 million documents from my MongoDB database using Spring Data MongoDB. Performance is a key concern, so I would prefer not to fetch all 1 million records at once. Is there a specific method within Spring D ...

"Exploring the dynamic trio of Ajax, JavaScript

Seeking assistance with passing a variable between PHP and JavaScript in my code. I have two PHP files - one for viewing and the other for processing, along with a JavaScript file for handling ajax requests. Review of my global.js file: window.onload ...

Create div elements using JSX and add them to an array

I am working with a structure that looks like this: var circle = { 'one': {items: []}, 'two': {items: []}, 'three': {items: []}, 'four': {items: []} }; Each items array needs to contain 10 unique ...

Your browser's popup blocker is preventing the file from being downloaded

I am encountering an issue with my PHP file download function where the browser's popup blocker is preventing the file from opening. My objective is to create an HTML form submit button that will send a form, modify an RTF file on the server based on ...

Implementing Bootstrap JavaScript functionality within a Rails 7 application

My current Rails 7 application utilizes esbuild as the JS bundler and has bootstrap imported. I am facing an issue where I am unable to access any Bootstrap Javascript functionality outside of the main application.js file. For example, I am attempting to p ...

AngularJS Treeview - Rearranging tree nodes

My journey with Angular is just beginning, and I managed to create a treeview following this example: jsfiddle.net/eu81273/8LWUc/18/ The data structure I've adopted looks like this: treeview1 = [ { roleName: "User ...

Getting the Object Id from HTML and passing it back to the Controller in MVC using C#

JQuery: $("#shoppingCart").droppable( { accept: ".block", drop: function (ev, ui) { var droppedItem = $(ui.draggable).clone(); $(this).append(droppedItem); $.ajax({ type: "POST", ...

Troubleshooting the Cross-Origin Resource Sharing Problem in Angular and

I had my client hosted on localhost:8080/ and the server on localhost:44302/ I am attempting to connect to my backend, but I keep encountering CORS issues. Here is my Angular http request: $http.post(url, data, { headers: { ' ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...