Exploring the world of JavaScript: leveraging Axios for writing data into mongoDB

Struggling with understanding Promises and implementing them on the backend. Even after reading multiple stackoverflow posts, it seems like I'm not alone.

I specifically need assistance on passing the result of a resolved promise within my code. In the snippet below, I am fetching data from the starwars API using axios.get, which returns a promise. I then resolve it using .then and want to write it onto a MongoDB atlas collection.

The frontend scenario, such as React's setState method, works fine when changing state within the .then function. However, I'm encountering difficulties making it work in the backend environment.

If you could guide me on the necessary changes needed to successfully write to MongoDB Atlas, that would be greatly appreciated.

var axios = require("axios");
const MongoClient = require("mongodb").MongoClient;
var db;

const getData = () => {
  return axios
    .get("https://swapi.co/api/people/1")
    .then(response => {
      if (!response.data) throw Error("No data found.");
         console.log(JSON.stringify(response.data))  **//This returns the data as expected.**
         return JSON.stringify(response.data);
    })
    .catch(error => {
      console.log(error);
      throw error;
    });
};

console.log(getData()); **// This returns {Promise <pending>}**

const client = new MongoClient(process.env.MONGODB_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Connect to database and insert default users into users collection
client.connect(err => {

  console.log("Connected successfully to database");

  let d = {
    name: "Luke Skywalker",
    height: "172",
    mass: "77",
    hair_color: "blond",
    skin_color: "fair",
    eye_color: "blue"
  };

  db = client.db(process.env.DB_NAME);
  db.collection("macroData").insertOne(d);  //this works
  db.collection("macroData").insertOne(getData); // this doesn't work as it still appears to  be a promise
});

Answer №1

fetchData() is a function that returns a Promise, requiring you to wait for it to resolve before proceeding. One simple approach is to insert the data once it becomes available:

  client.connect(err => {
    // ...
    fetchData().then(data => {
      db.collection('macroData').insertOne(data)
    })
  })

Alternatively, if you prefer using async/await:

client.connect(async err => {
  // ...
  const data = await fetchData()

  db.collection('macroData').insertOne(data)
})

Answer №2

Make sure to place your mongodb call within the axios promise in order to utilize the resolved promise for updating your database. This was a stumbling block for me as well...

The following code is in reference to Nick's comment, since the code couldn't be posted due to length restrictions. Make sure you have a database named 'test' or any appropriate name here let datab = client.db('test'). The default setting should create a 'test' database when using MongoDB Atlas. If you update your username and password in the mongoURL, everything should work smoothly. Hope this helps. This snippet creates a 'starwars' entry under 'test.starWarsData'.

let axios = require("axios");
let MongoClient = require("mongodb").MongoClient;
let mongoParams = { useNewUrlParser: true, useUnifiedTopology: true };

let mongoUrl =
  "mongodb+srv://user:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16667765656179647256757a6365627364263b7e7875227f38776c636473387b79787179727438787362">[email protected]</a>/test";
//try feeding just the object e, and see if it works, in case your axios error catching is not great.
let e = {
  a: "this is a",
  b: "this is b",
  c: "this is c",
  d: "this is d"
};

let newUrl = "https://swapi.co/api/people/1";

console.log(newUrl);

let client = new MongoClient(mongoUrl, mongoParams);

client.connect(err => {
  if (err) {
    console.log(err.message);
    throw new Error("failed to connect");
  }

  let datab = client.db("test");
  console.log("db connected");

  try {
    axios.get(newUrl).then(res => {
      try {
        datab.collection("starWarsData").insertOne(res.data);
        console.log("insert succeeded");
      } catch (err) {
        console.log("insert failed");
        console.log(err.message);
      }
    });
  } catch (err) {
    throw Error("axios get did not work");
  }
});

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

Using Javascript to Style the HTML and Body Elements

If you want to set the height of a div in CSS so it extends from the top of the page to the bottom, you can do it like this: html, body, #xdiv { height: 100%; min-height: 100%; } The issue is that this code runs immediately, so when content loads ...

Utilizing Angular's asynchronous validators to handle incoming response data

Struggling with async validators in Angular and trying to implement Container/Presentational Components architecture. Created an async validator to check for the existence of an article number, with the service returning detailed information about the arti ...

Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages. Has anyone encountered this issue before? The goal is ...

Struggling to grasp the importance of ensuring the security of axios requests

I am struggling to grasp the security implications of using Axios requests. Situation I have a basic button that allows users to register with a random string through a post request. This post request is then processed by my express server, which ...

Is there a way to dynamically update an image source using JavaScript based on the device size?

I am attempting to switch the image source using JavaScript. Specifically, when the window size is max-width: 576px;, I want it to change to a different image source that fits the aspect ratio of mobile devices. This element is part of an image slider. I ...

The issue with Firefox's DOMContentLoaded event

After creating a script that interacts with the Dom, I noticed that it needs to wait until the Dom is ready before executing each operation. My intention is to make this script usable in two ways: Include it in the head tag, ensuring it loads before the ...

Change button text with JS on click

My goal is to update the text on a button click, changing it from 'Copy' to 'Copied!' as part of a custom clipboard implementation. The code I'm currently using is as follows: HTML: <button id="copyButton2">Copy</button& ...

What is the best way to store the results of a .each loop in an array?

When I call the function: CreateNode(e,control);// which will return an ID. // e i leave alone, but i was thinking that i // could pass the object into the function this way optionally. function CreateNode( ...

During the construction process, assign the newly created object to a different entity

For the purpose of streamlining my logging process, I decided to create a function that generates a winston.Logger instance with the appropriate transports already set, and then returns that logger. Although everything is functioning correctly, ESLint is ...

What is causing the list-sorter to malfunction?

This website crashes when executed: <head> <script> var numbersList = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]; var orderedList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...

Organize items with comparable information and adjust using mongoose

Organizing Array of Objects by User in Mongoose Retrieve Specific Item from Array Using Mongoose Aggregation I am looking to group the objects within an array and reformat them as per my requirements data:[ { user_name: 'Jenny Lawrence& ...

Creating navigation with routed URL in ASP.NET MVC

I'm having trouble with the navigation in asp.net mvc and handling URLs. For example, when you visit your profile on Facebook, the URL is facebook.com/yourusername. On your profile page, there is a menu with links such as Timeline, About, Friends, et ...

Show Text When Clicking Within Separate DIVs

I have a set of three divs. One contains a Twitter icon, another holds a LinkedIn icon, and the last one is designated for displaying text upon clicking. My goal is to click on the Twitter icon and have corresponding text appear in the third div. Then, if ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

encountering a 'TypeError': The function user.save() is invalid

When attempting to save user data to the database using mongoose, I encountered a problem: To give users credits, I am charging them "money" with the stripe library. However, when trying to post the data to the database, I receive this error message - Typ ...

Show a single item using Vue.js

I am facing an issue with a list of items where the title serves as a link to display a detailed view of the item. Upon clicking the title, it should take me to the correct URL + ID. However, in the Vue tools, when I retrieve the item with the matching ID ...

How can promises be used in place of executing multiple mongoose queries?

Looking for a solution to avoid nested callbacks in the following code: app.get '/performers', (req, res) -> conductor = require('models/conductor').init().model soloist = require('models/soloist').init().model ...

Do unique document ids get embedded within the collection?

Exploring a Mongoose Schema with Nested Embedding: var EmbedSchema = new Schema({ foo: String }); var ParentSchema = new Schema({ foo: String, embeds: [EmbedSchema] }); Once I create and nest some objects, the structure will look like this: { " ...

Setting up Firebase and Vue: Best practices for initializing Firebase and Vuefire

I am encountering an issue while setting up Vuefire and Firebase in my application. The error that I see in the console is: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). at initializeApp (webpack ...

Manage the orientation of an object circling a sphere using quaternions

My latest game features an airplane being controlled by the user from a top-down perspective, flying over a spherical earth object. The airplane has the ability to rotate left or right by using the arrow keys on the keyboard, and can accelerate by pressing ...