Updating values in mongoDB using Express.js and axios: A step-by-step guide

I need help figuring out how to update a specific post's data in my mongoDB using its object id. I have created an HTML form that displays the selected post's data and allows me to make changes, then submit the updated data to http://localhost:5000/update-opportunity. In my backend, I am waiting for the form submission on this URL. However, I am stuck at using the id sent with axios to update the specific object in the database.

Below is the code I have:

Axios form submission in Vue component

axios.post('http://localhost:5000/update-opportunity', {
    id: this.id,
    company_name: this.company_name,
    company_type: this.company_type,
    lines_of_business: this.lines_of_business,
    client_type: this.client_type,
    contract_type: this.contract_type,
    contact_name: this.contact_name,
    contact_number: this.contact_number,
    email_address: this.email_address,
    opportunity_owner: this.opportunity_owner,
    decision_maker: this.decision_maker,
    annual_jobs: this.annual_jobs,
    average_fee: this.average_fee,
    annual_value: this.annual_value,
    next_steps: this.next_steps,
    due_date: this.due_date
})
.then((response) => {
    console.log(response);
    this.$emit('formSubmitted');
})
.catch(function (error) {
    console.log(error);
});

Backend form submission

router.post('/update-opportunity', (req, res, next) => {
    const db = getDb();
    db
        .collection('jobs')
        .insertOne({
            company_name: req.body.company_name,
            company_type: req.body.company_type,
            lines_of_business: req.body.lines_of_business,
            client_type: req.body.client_type,
            contract_type: req.body.contract_type,
            contact_name: req.body.contact_name,
            contact_number: req.body.contact_number,
            email_address: req.body.email_address,
            opportunity_owner: req.body.opportunity_owner,
            decision_maker: req.body.decision_maker,
            annual_jobs: req.body.annual_jobs,
            average_fee: req.body.average_fee,
            annual_value: req.body.annual_value,
            next_steps: req.body.next_steps,
            due_date: req.body.due_date,
            date_added: new Date()
        })
        .then(result => {
            res.status(201).send();
            console.log(result);
        })
        .catch(err => {
            console.log(err);
        });
});

Note: getDb() is my database connection function.

Answer №1

To update a record in MongoDB, you will need to use the "update" method.

Currently attempting to insert a new record.

Try implementing something similar to this:

const ObjectID = require('mongodb').ObjectID;

db.collection('jobs').update(
{"_id": req.body.id},
{$set: {
  company_name: new ObjectID(req.body.company_name),
  company_type: req.body.company_type,
  lines_of_business: req.body.lines_of_business,
  client_type: req.body.client_type,
  contract_type: req.body.contract_type,
  contact_name: req.body.contact_name,
  contact_number: req.body.contact_number,
  email_address: req.body.email_address,
  opportunity_owner: req.body.opportunity_owner,
  decision_maker: req.body.decision_maker,
  annual_jobs: req.body.annual_jobs,
  average_fee: req.body.average_fee,
  annual_value: req.body.annual_value,
  next_steps: req.body.next_steps,
  due_date: req.body.due_date,
  date_added: new Date()
}});

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

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

The arrow icon for selecting input in Material Dashboard React is missing

Source Code View Result Why is the arrow icon not visible when viewing the select like this? I am using "@mui/material": "^5.8.6". Can someone please help me with this? <Box sx={{ width: "auto" }}> <FormControl fullWidth> ...

Retrieving information from a local JSON file in Vue.js using the jQuery $.getJSON() method

Currently, I am in the process of developing a demo application using Vuejs which involves extracting map data from a local .json file. The extracted data is then used to obtain specific information like latitude and longitude values that are necessary for ...

Is there a way to dynamically insert objects into an array from an ajax json request, in order to iterate through them later on?

I have a current code where I am trying to utilize data to create a new information window from the Google Maps API dynamically. Currently, I am pushing objects of different data types into an array, but I believe that might be the only issue here. How c ...

Tips on changing an image with a button click

I am currently working on a project where I have a div tag containing an image that is selected randomly from different arrays based on topics. However, I am facing some challenges in making the image change when the "go" button is clicked. I want the if ...

Having trouble loading items in a <select> tag with Jquery?

Dealing with a seemingly simple issue, I am struggling to figure out how to load items into a select using jQuery. Working with the Materialize theme available at: The code snippet in question: <div class="input-field col s12"> <s ...

Only scroll the div if it is not within the visible window

I've been looking at this snippet: The sidebar division is what I'm focusing on right now. I want the div to scroll along as I scroll down the page, but I need it to stop scrolling when its bottom is in view. The same should apply when scrollin ...

What is the preferred method for implementing a dynamic select control with Ajax

I'm having an issue with AJAX and MySQL in PHP. Can anyone offer assistance? Within my form, I have a select control: <form action="index.php" method="post" name="pretraga" class="border"> <p>Location:</p> <div ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

Unable to process JSON array

One issue I'm facing is with an 'onload' handler for my web page. The javascript function 'handleLoad()' that it calls has suddenly stopped working, specifically not being invoked after attempting to pass the output of json_encode ...

Utilize jQuery's addClass Method when Submitting a Form Using Ajax

When the form is submitted, I would like to add a class and display a loading animation before executing the AJAX request. However, when setting async to false in the AJAX call, the AJAX request will be executed first before displaying the loading animatio ...

What could be causing the repeated calls to a computed function in vuejs?

In my Vuejs application, I start by fetching initial data and setting it in the store: const app = new Vue({ router, store, mounted: function() { var that = this; $.get("/initial_data/", {}, function(data) { that.$s ...

Using JQUERY to store the ID of a div along with its checked value in a multidimensional array

I am looking to create an array that stores the ID of a div and the checked value. Check out this FIDDLE for reference For example, if I check samsung and lenovo under brands, and select 4gb for RAM, the array should be: array[ ] = ["brands" ...

Guide on loading xml information from a web browser using JavaScript

I have been working on loading data from the browser using a URL and currently utilizing JavaScript to achieve this. window.onload = function() { // This is the specific URL I am attempting to load data from. // The XML fi ...

JavaScript Tutorial: Simplifying Character Ranges for Conversion

I am currently working on adapting code I found here to create a virtual keyboard for a foreign alphabet using an online textarea. Below is the modified code: <textarea id="txt"></textarea> <script src="https://ajax.googleapi ...

Select items from object based on a specified array of IDs

I am facing a challenge with my list of objects that each have an array associated with them. For instance, take a look at this example: "-KpvPH2_SDssxZ573OvM" : { "date" : "2017-07-25T20:21:13.572Z", "description" : "Test", "id" : [ { ...

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

Retrieve the past week's data based on names using JavaScript

Is there a way to dynamically fetch the past seven day names, starting from today, in JavaScript? I am looking to format the result as follows: (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday). ...

What is the procedure for determining the type of an object in a GraphQL schema?

My mongo schema for todo items looks like this: const todoSchema = new Schema( { userId: { type: String, required: true }, title: { type: String, required: true }, due_date: { date: { type: Number }, month: { type: Number }, ...