What is the process for using express and Postman to send a PUT request and modify a specific field in MongoDB?

I'm struggling to figure out how to use a MongoDB document's id in the route and manipulate the 'balance' field using Postman. Here's what my code currently looks like: My route:

router.put('/:id', async (req, res) => {
const id = Account.findById(req.params.id);
const updatedAccount = await Account.findByIdAndUpdate(id,{
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    balance: req.body.balance
});
res.end(JSON.stringify(updatedAccount))
});

My model:

const AccountSchema = new mongoose.Schema({

firstName: {
    type: String,
    required: true,
},
lastName: {
    type: String,
    required: true,
},
balance: {
    type: String,
    required: true
}
}, { collection: 'account'});

Answer №1

For better efficiency, I suggest breaking down the operations into distinct steps (such as finding first, then updating, and finally saving). You can implement something along these lines within the callback function of your put handler:

const updates = Object.keys(req.body)
try {
        const account = await Account.findById(req.params.id)
    
        updates.forEach((update) => account[update] = req.body[update])
        await account.save()
    
        if (!account) {
            return res.status(404).send()
        }
    
        res.send(account)
    } catch (e) {
        res.status(400).send(e)
    }

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

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

In what way can I decipher a section of the URL query string within my AngularJS application?

Here is a snippet of code that I am working with: var search = $location.search(); if (angular.isDefined(search.load) && search.load != null) { if (search.load = "confirmEmail") authService.confirmEmailUserId = search.userI ...

Express and Angular 2 Integration in package.json

Hello, I am new to learning Angular 2 and have a better understanding of Express. One thing that is confusing me is the package.json file, particularly the "start" part. Here is my package.json when I only had Express installed: { "name": "Whatever", ...

The size of the popup does not align properly with the content within it

After creating an extension for Chrome, I specified the dimensions of the popup to be 600 x 300 px. Everything was working perfectly until Chrome updated to version 27. As shown in the screenshot, I set the width and height using CSS, but there is still a ...

Configuring Nginx for hosting an Angular application with a Node.js API

I have built an API using Express and a front-end using Angular. Both are located in different directories named /var/www/apps/client and /var/www/apps/server. Now, I am trying to deploy my application using Nginx as a web server. While I can successfully ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

Unable to transmit Props to Component - Fluctuating Behavior

I developed a React.js and Next.js application where I needed to pass the User object to all pages. My plan was to then pass this User component to the Head component in order to display different navigation options based on the user's role. Here is w ...

Leverage Nuxt without the need for a builder in your code

Currently, I am utilizing Nuxt programmatically within Express using the Nuxt.render middleware as shown below. const { Nuxt, Builder } = require('nuxt') const app = require('express')() const api = require('../api') app.use( ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...

Triggering OnClick() more than once may result in the function failing to execute as intended

My dilemma involves a table of cells where clicking a cell triggers an event. I need to dynamically add cells, so I plan to call OnClick again on all rows. But when I do so for the second time, cells that have already had OnClick called twice stop firing a ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...

Is there a versatile spell-checking tool available for HTML text boxes?

When designing a text box in HTML, I want to provide real-time input validation and spell check for the user's text. My goal is to underline any spelling mistakes as they type. This seems like a basic feature, but I've yet to find a plugin or AP ...

Failed to interpret Firebase ID token decoding

My approach involves restricting my API to only logged-in users by sending a Firebase token and attempting to verify it on the server-side, following Google's guidelines precisely as mentioned here. However, I encounter an exception that reads: Fire ...

"Displaying mongoose date in the HTML5 input type date format (dd/mm/yyyy) is a simple process that can

I have a structured data in MongoDB as shown below: var Person = new Schema({ "Name": { type: String, required: true }, "DOB": { type: Date, "default": Date.now } }); An instance of this schema is created using NodeJs with mongoose ODM: { "N ...

What is the best way to save and reload a canvas for future use?

My current setup involves using PDF.js to display PDF documents in a web browser. The PDF.js library utilizes canvas for rendering the PDF. I have implemented JavaScript scripts that allow users to draw lines on the canvas by double-clicking, with the opti ...

Challenges with loading content and async JavaScript within websites

I decided to replace the content on index.htm with the content from project.htm. By clicking on a#front, it redirects to project.htm and dynamically updates the content. However, I am facing an issue regarding how to run the javascript that accompanies thi ...

Tips for fetching form data transmitted via HTTPS in Node.js?

As someone new to back-end security, I'm hoping for some guidance without judgement: When receiving values over HTTP in my node application, the form data is easily accessible in the request object using req.body.{name of input element} However, whe ...

What is the best way to pass a div element and a variable from a Child component back to a Parent component in Next.js/React?

My goal is to create a webapp that, when an item in the list generated by the child component is clicked, displays the corresponding image in a div within the parent component. After some trial and error, I managed to generate the list in the child compone ...

Is there a way to seamlessly share TypeScript types between my Node.js/Express server and Vite-React frontend during deployment?

I'm currently tackling a project that involves a Node.js/Express backend and a Vite-React frontend. My goal is to efficiently share TypeScript types between the two. How should I configure my project and build process to achieve this seamless type sha ...

Error: Attempting to access 'imageName' property on an undefined object

I have been honing my skills in constructing restful APIs with node.js along with MongoDB. In my router, I utilize the router.delete method. Within this method, I perform two crucial operations. Firstly, I search for and select the productImage based on th ...