JavaScript: Struggling to send new data to mongodb REST API via POST request

After spending time developing a REST API that displays information about the planets in our solar system on a local server in .JSON format, I encountered an issue with POST requests. Although GET requests were successful when testing the URL (localhost:8000/planets) using Postman, I struggled with POST requests.

When switching from a GET request to a POST request on Postman by typing localhost:8000/planets, entering data, and sending it, the newly added data appeared after a subsequent GET request. However, making changes to the JavaScript file containing the code for POST and GET requests led to the disappearance of the posted data upon performing another GET request on Postman. This unexpected behavior has left me puzzled, indicating a possible issue within my code. Here is the code snippet:

(Code Snippet Provided)

In one instance, while attempting to add data for Neptune, everything seemed to function properly as the new data was visible alongside existing planet information following a GET request on Postman. Yet, upon rectifying a minor typo in the JavaScript file and conducting another GET request, the Neptune data vanished. The confusion surrounding this inconsistency prompts me to seek assistance in resolving this perplexing matter.

Answer №1

The reason for this issue is that each time you reload your JS file, the following code executes:

var Planet = mongoose.model('Planet', planetSchema);
Planet.collection.drop();

This action results in deleting all your data and then re-adding the initial data again. Therefore, any data that was POSTed will be lost.

It's important to consider how you are hosting the node file. If you are using nodemon or a similar tool that automatically refreshes the server whenever a change is made to the file, this behavior is what causes your data to disappear. The drop command is being re-executed every time you make a change, hence the loss of data.

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

Android List View - Navigate to a website when clicked

Apologies if this question sounds inexperienced, but I am not very familiar with Android. I have a MainActivity.Java file that uses JSON data retrieved from a server to populate a TextView. The parameters received from the server include id, username, mes ...

Guide on selecting a specific title attribute as the chosen option in Angular by utilizing Bootstrap's selectpicker

I encountered an issue where some of the options in my select element have the same value, making it difficult to choose the correct one using setValue(...). As a workaround, I attempted to use 'selected', but unfortunately it did not yield the d ...

Populating a dropdown with a list by utilizing the append grid library

Hey there! I'm currently using the jquery appendGrid plugin to display a drop-down menu in one of the columns. In the code snippet below, the column labeled "Origin" has a drop-down option that is working as expected. $(function () { // Initializ ...

Swap out The div element with the html() method

I'm encountering an issue when trying to swap out a div element with ajax. My goal is to create a start/stop button functionality. The page displays a list of card elements, each with its own button, which are stored in separate html files. work_orde ...

Using AJAX to send JSON data to PHP for querying MongoDB

I am creating a new JavaScript object. To associate the user who is currently logged in (using a session variable), I am saving the user's ID as an attribute using AJAX. My goal is to send this object as JSON via AJAX to a PHP file, which will then i ...

Having trouble with a Parsing Syntax Error related to "Export Default" in React Native Typescript?

I am encountering an issue with my React Native project when transpiling Typescript code. The error occurs in the simulator during build, and seems to be related to using export default in Typescript for component export. This error arises as a parsing iss ...

Separate the information into different sets in JavaScript when there are more than two elements

Upon extraction, I have obtained the following data: ╔════╦══════════════╦ ║ id ║ group_concat ║ ╠════╬══════════════╬ ║ 2 ║ a ║ ║ 3 ║ a,a ...

Dealing with withdrawn requests in Express/Node.js and Angular

When a client or browser cancels a pending HTTP request, it appears that Node with Express continues to process the request, keeping the CPU busy with unnecessary tasks. Is there a way to instruct Node.js/Express to stop these pending requests that have be ...

What is the best way to utilize ajax for uploading both a text field and a file simultaneously?

I am currently new to AJAX and working on implementing a form that uploads a name and a file to a PHP file for processing and insertion into a database using mysqli. While the PHP file works, I am facing issues with the AJAX code. I have tried implementati ...

How can I integrate vue-cli output into a PHP project?

One benefit of using vue-cli is that it automatically sets up a local server for you. I'm curious, can I utilize the output from vue-cli in a PHP project (such as app.js )? Another question I have is related to the local network - How does it suppo ...

"Creating eye-catching popup images in just a few simple steps

<div className="Image popup"> <Modal isOpen={modalIsOpen} onRequestClose={closeModal} contentLabel="Image popup" > <img src="../img/navratri-1.png" alt="Image popup" /> <b ...

What is the best way to parse JSON data in a Struts 2.0 web service

When working in a servlet, I typically use the JSONObject json = (JSONObject)new JSONParser().parse(jb.toString()); code snippet to get a JSON object and JSONObject result=new JSONObject();response.getWriter().write(result.toString()); to post a JSON obj ...

Command for Pinging in Discord.js

I attempted to create a ping command for my bot, and here is the code I used: client.on('message', message => { if (message.content === '+ping') { message.channel.send(` ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

How can I extract information from Firebase and set it in the this.props of a React component?

Hey there, I'm having some trouble with my Firebase setup. I need to transfer data from snapshot.val() into this.props.device, but when I try to do so within the this.firebaseRef.on() function, 'this' is showing up as 'null'. Any s ...

Modifying the location of an element in an array with jQuery

Using jQuery and JavaScript var movableItems = new Array(); movableItems.push($('#cloud1')); movableItems.push($('#comment1')); if(leftPressed == true){ for(var i = 0; i < movableItems ...

Guide on scheduling a daily API GET request in a Node.js script for 11:00pm

I am working on a node js application that involves making an AWS API GET call. http://localhost:3000/amazon/api Within this call, I have specified the necessary functionalities. My goal is to automate this call to run everyday at 11:00PM using node js ...

Convert information into a dictionary containing integers and lists

I currently have data stored in my database in the following format: ID DateID Country NoOfPeople 2 20130301 Indonesia 2 3 20130301 Malaysia 128 4 20130301 United Kingdom 2 6 20130302 Australia 1 24 201 ...

Displaying success and failure messages on a modal window using Ajax in PHP form

Unable to display error messages or success messages in the same modal window. I have set up Wordpress and using the following code: Form <form id="formcotizador" method="post" action="<?php echo get_template_directory_uri(); ?>/cotizador/procc ...

The mongoose fails to establish a connection with the Mongo Db Atlas

I am having issues with my simple node express app when trying to connect to MongoDB atlas. Despite deleting node_modules and re-downloading all packages, I am still encountering the same error. The specific error message reads as follows: Cannot read pro ...