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

The appearance of my website appears differently depending on the resolution

Just recently, I began exploring the world of HTML/CSS/JS and created a handy tool for my personal use. However, I encountered an issue when viewing it on different resolutions which caused some elements to look distorted. The tool I made allows me to inp ...

What can you do when encountering the error "Unexpected token" in Node.js?

While attempting to save the Node JS code, I encountered an error message stating 'Parsing error: Unexpected Token'. Please note that Mongo is connected. I have made adjustments to the curly brackets and semicolons, but the issue persists. What ...

Validating groups of fields using Angular fieldsets

AngularJS validation is working well with ng-required. However, I am interested in checking if all the form elements within my fieldset are valid. <form> <fieldset> <legend> Part one <img src="/co ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Assigning array materials in ThreeJS allows you to create complex

When I assign framemat to createScene(ID, geometry, 1, framemat), everything works fine. But when I try createScene( ID, geometry, 1, materials[ID] ), it doesn't cooperate. var jsonLoader = new THREE.JSONLoader(), paths = [ "obj/jgd/ ...

"What exactly does {...props} refer to and what is the best way to obtain my function from another

Currently, I am focusing on learning react native with a specific interest in react navigation v5. As mentioned in this resource: https://reactnavigation.org/docs/themes/#using-the-current-theme-in-your-own-components, my goal is to implement a dark mode ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...

Putting an <input/> element inside a Material UI's <TextField/> component in ReactJS - a beginner's guide

I am attempting to style <TextField/> (http://www.material-ui.com/#/components/text-field) to resemble an <input/>. Here is what I have tried: <TextField hintText='Enter username' > <input className="form-control ...

What is the process for retrieving a detached element?

In the game, I'm looking to provide a "start again" option for users when they lose. The .detach() method comes in handy for hiding the button initially, but I'm struggling to make it reappear. Some solutions suggest using the append() method, bu ...

Is there a way to ensure that a "catch all other" route in the Vue Router will also capture the URL if a portion of it matches a predefined route?

After following the suggestion to implement a catch all route from this article, I realized that it does not capture URLs that partially match a defined route. routes: [ { path: "/album/:album", name: "album", component: Album, } ...

Switching from jQuery to vanilla JavaScript, iterating through each HTML tag in a loop

Here is my current jQuery code that I am looking to convert into vanilla JavaScript. var elements = []; document.querySelectorAll('*:not(script, style, iframe)').forEach(function(element) { elements.push(element); }); I have tried using d ...

Pulling information from MongoDB within a specified price range using Node.js

I am currently working on fetching data within a specified price range from the property model. For example, if a user provides a minimum and maximum price, I want to display the number of properties that fall within that price range. I have indexed the ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Using the connect-flash package to display a flash message on the website

Currently working on learning expressjs and mongodb through various exercises. I am attempting to display flash messages whenever a new item is added, updated, or deleted from the database. Struggling with getting it to work as expected without any errors ...

Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images. The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the s ...

Unable to retrieve any results from MongoDB when using the $in operator, experiencing unexpected behavior

Apologies for the not-so-great title, having trouble summarizing the issue accurately. In my Schema, I have defined the language field as an array of strings: 'language': [String] When sending a GET request in the router: let page = Math.max(0 ...

What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList ...

Await that's locked within a solo asynchronous function

async function submitForm(e){ e.preventDefault() console.log(e.target) try { const response = await axios.post('/api/<PATH>', {username, password}); console.log(response.data); const token = response.data.token if (t ...