Tips for importing data from Google Sheets to MongoDB Atlas Realm

I'm attempting to transfer my Google Sheets data to MongoDB Atlas. I've created the app script and function in the editor. However, when running the code in MongoDB's function editor, I encounter the ERROR "mongodb insert: argument must be an object". Here is an overview of my progress:

Google Sheet APP Script

function exportSheetsToMongo () {

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName("US");
  var headersRows = 1;
  var range = sheet.getDataRange();
  var numsRows = range.getNumRows;
  var data = range.getValues(); 

  for (var i = headersRows; i < numsRows; i++) {
    var usZipIdCell = range.getCell( i +1, columns.zip+1) // Error possible here
    // var description = data[i][columns.description];
    
    var formData = {
      // 'country': data[i][columns.description],
      'zip': data[i][columns.zip],
      'city': data[i][columns.city],
      'state': data[i][columns.state],
      'state_code': data[i][columns.state_code],
      'county': data[i][columns.county],
      'county_code': data[i][columns.county_code],
      'lattitude': data[i][columns.lattitude],
      'longitude': data[i][columns.longitude],
      'accuracy': data[i][columns.accurcay]

    };
    var options = {
      'method':'post',
      'payload': formData
    };
    if(description) {
      var insertID  = UrlFetchApp.fetch("https://us-east-1.aws.data.mongodb-api.com/app/mmc-backend-mzbhi/endpoint", options);
      usZipIdCell.setValue(insertID)
    }
  } 
}

MongoDB Realm Function Editor

exports = async function(payload) {
  
  const mongodb = context.services.get("mongodb-atlas");
  const eventsdb = mongodb.db("us_zip");
  const eventscoll = eventsdb.collection("zip");
  const result = await eventscoll.insertOne(payload.query);
  var id = result.insertedId.toString();
  if(result) {
    return JSON.stringify(id,false,false);
  }
  return {text: 'Error saving'}
};

Partial Google Sheet Data

https://i.sstatic.net/FHMe3.png

Data Base

https://i.sstatic.net/ZLEfR.png

Answer №1

The problem might lie in the data manipulation process. It is important to convert the data into a string format and specify the application type. Additionally, it seems like you are referencing payload.query instead of payload.body. To address this issue, consider implementing the following code snippet:

    var formData = {
      ...
    };
    var options = {
      'contentType': 'application/json', // Specifying JSON application body type
      'method':'post',
      'payload': JSON.stringify(formData) // Converting the data into a string
    };
    if(description) {
      var insertID  = UrlFetchApp.fetch("https://us-east-1.aws.data.mongodb-api.com/app/mmc-backend-mzbhi/endpoint", options);
      usZipIdCell.setValue(insertID)
    }
exports = async function(payload) {
  
  const mongodb = context.services.get("mongodb-atlas");
  const eventsdb = mongodb.db("us_zip");
  const eventscoll = eventsdb.collection("zip");

  const body = JSON.parse(payload.body.text()); // Parsing the body of the 'request'

  const result = await eventscoll.insertOne(body);
  var id = result.insertedId.toString();
  if(result) {
    return JSON.stringify(id,false,false);
  }
  return {text: 'Error saving'}
};

It is also advisable to utilize eventscoll.insertMany() instead of eventscoll.insertOne() to minimize the number of url calls made for each entry in your sheet.

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

jQuery Dragging Element With Restricted Area Overflow Hidden

This scenario involves dragging a wider element than its parent, which has the CSS property overflow set to hidden. The parent's width and overflow settings are fixed and cannot be altered. Below is the HTML code: <div class="container"> < ...

Encountering issues with Webpack 2 failing to resolve the entry point specified in the

Encountering an issue while trying to compile my application with webpack 2. This is how my app folder structure looks: / | - dist/ | | - src/ | | | | - modules/ | | | | | | - module1.js | | | | - index.js * | | _ webpack.config.js | | ...

How can you use Redash to generate a visual representation that displays the frequency of different categories?

I am attempting to replicate a chart similar to the one shown in this example: However, I am struggling to do so. If anyone could provide guidance on how to create this particular chart, it would be much appreciated. You can assume that I am working with ...

Can we create a process that automatically transforms any integer field into a hashed string?

Is there a non-hacky way to hash all IDs before returning to the user? I have explored the documentation extensively but haven't found a solution that covers all scenarios. I am working with Postgres and Prisma ORM, managing multiple models with rela ...

Will the rel attribute work in all web browsers and with all HTML tags?

Confirming that it is compatible for use with JQuery scripting. ...

Locating the index of the initial duplicate in an array using Javascript

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4]; I’m looking to write a function called indexOfRepeatedValue (array) that utilizes the numbers stored in the provided variable. The function should create a variable called firstIndex. Within a for loop, deter ...

Is the HTML5 video backup image misplaced?

Here is the HTML I created to showcase a video background with two fallback images for mobile and old browsers: <div> <video id="video_background" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0"> <!--<source s ...

When clicking on an item in the wishlist, only the text for that specific item should change,

Hi all, I'm in need of some assistance. I have successfully created a wishlist toggle where clicking on the heart icon changes it from an outline to solid. However, my issue lies in changing the tooltip text from "add to wish list" to "added to wish l ...

One of the two buttons on the form must be selected

Within a form, I have implemented two buttons that are structured like this: <button name="option" id="option" value="A" class="btn btn-outline-primary" onclick="storeTime()"> Select Option A </but ...

What is the best way to integrate SVGs into a React project after transitioning from Vanilla JavaScript?

I am currently diving into an Advanced CSS course that explores the implementation of SVG's. However, the approach involves Vanilla JS whereas I aim to incorporate it into a React project. When using Vanilla JS to embed an SVG into a button, you typi ...

Sending an array via an AJAX POST request using jQuery

I'm having trouble with my POST function not passing the data[] array. Can someone confirm if my array is correct? Or perhaps there's something missing in my POST function? function doAction(prefix) { if ($('#' + prefix + '_actio ...

Front-end React app paired with a backend Express server, both running through a Nginx server

After hours of searching on Google and watching YouTube videos, I have yet to find a solution to my issue. My setup includes a React app frontend running on Nginx. The frontend makes Axios requests like the following example: await axios.post("htt ...

Issue with retrieving an array of objects in an Angular function

Good day, I am facing an issue when attempting to retrieve an array of objects from an external function. I have defined a class called Object with 2 properties, a constructor, and a method that returns an array containing more than 50 objects. For this e ...

Utilizing Bootstrap 5: Executing JavaScript exclusively upon successful form validation

I've created a form with multiple input fields that are being validated using Bootstrap 5 validation. <form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate> ...

Attempting to conceal certain elements based on the current route in Angular 5

Trying to create a dynamic navigation system where different items are displayed based on the website path. For example, if the path is http://mywebsite.com/path, certain navigation items should be hidden while others are shown. My current setup includes. ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Identifying the unique parent component of a component within Angular

One of my components, named Com1, is imported into multiple other components. Within Com1, there is a button that triggers a function when clicked. In this function, I am trying to print out the parent component of the specific instance of Com1. How can I ...

React: Dealing with null values when making a PUT request using axios

I have a list obtained from an external API through the use of axios. Each element in the list is an editable input field with its own corresponding update button. Upon modifying the data in an input, and while executing a PUT request to update it, consol ...

Utilizing the variable's value as a parameter in a jQuery selector

I am having trouble replacing $('#divy a:lt(3)') with the variable instead of a hard-coded number like $('#divy a:lt(count)'). Check out this Fiddle for more information. var timerId, count = 0; function end_counter() { $('# ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...