Create an additional data field in an existing resource using the PUT method

Incorporated Google authentication into my NextJS application. The process involves the user making progress within the web app, which is stored in local storage as an array. If the user decides to register, I receive the session back and then send a PUT request to update the document in the database by adding a new field (array) from local storage.

I have successfully implemented a GET request that retrieves user data based on their email. Now, I am facing the question of how to insert a new field using the PUT method. In this scenario, the field is an array called "progress" and I am unsure whether to use the "update" method.

Below is an example record from my MongoDB:

_id: 63cc85641624a77f17ca5f29
name: "John P"
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563c393e38782616313b373f3a7835393b">[email protected]</a>"
image: "https://lh3.googleusercontent.com/a/AEdFTp7xzF4eYtyhTgRxmgP4vYdCqDa6zW…"
emailVerified: null

The goal is to add a new field: progress: ['some data']

Here is the PUT request I am working with:

      case 'PUT':
        const updateData = await fetch(`${baseUrl}/updateOne`, {
          ...fetchOptions,
          body: JSON.stringify({
            ...fetchBody,
            filter: { email: email },
            update: {}   <---------------!!!!!
          }),
        })
        const updateDataJson = await updateData.json()
        res.status(200).json(updateDataJson.documents)
        break
      

Answer №1

To modify your document with the updateOne method and include a new progress field, you can implement the following code snippet:

filter: { email: email },
update: {$set: {progress: arr}}

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

Encountered an issue with cookie handling during the process of authenticating users through supabase/ssr using Google OAuth

I am developing a Next.js project with the integration of Supabase. User authentication is done through Supabase clients using Google OAuth providers. I have followed the exact code from this GitHub repository: https://github.com/SamuelSackey/nextjs-supaba ...

Restricting access to my API to only permit communication with my designated front-end application

Currently working on developing a node/express backend and looking to establish an API that is exclusively compatible with my reactjs frontend (private API). Let's take the example of an e-commerce platform where users can browse products, make selec ...

Can Next.js support a one-time server-side startup method?

I am looking to customize the default parsing of numeric types returned by node-postgres, as described in this resource. I want to implement this change globally in my application. Here is the snippet from the documentation... var types = require('pg& ...

Warning: Attempting to destructure the property 'name' from 'req.body', which is undefined, is causing a TypeError

Currently, I am diving into the world of MERN Stack web development and running into a unique issue. When using Postmate to input data from the body to the database, everything works smoothly when done from the server.js file. However, when attempting the ...

Why is it that even though I update the state using useState, when I try to access the state afterwards,

I have been working on a function that updates my states dynamically. Here is the code snippet: const refreshAfterCreate = async () => { try { const res = await fetch(process.env.NEXT_PUBLIC_MICROSERVICE_COMPANY_URL + '/companies&apo ...

What causes styled-components to apply styles in a unique way to its descendants?

My parent component has some specific styling: > * { width: initial; } Within this parent component, I have two separate child components: <Component1/> and <Component2/> Both of these components are div elements with a width of 200 ...

Using node.js and mongoDB: Retrieve a custom value if the field is empty

My goal is to query the database for documents and if a certain field is not set, I want to replace it with a custom value. Let's say I have a collection of songs in my database where some have 'pathToCover' set and some don't. In those ...

It can be frustrating to have to refresh the page twice in order to see changes when utilizing the revalidate feature in Next

When I make the REST call to fetch data for my page using the code below: // src/app/page.js const Home = async () => { const globalData = await getGlobalData(); return ( <main'> <SomeComponent data={globalData} /> < ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

Resolved the time zone problem that was affecting the retrieval of data from the AWS Redshift database in Next

Currently utilizing Next.js for fetching data from AWS Redshift. When running a query from DataGrip, the results display as follows: orderMonth | repeatC | newC 2024-02-01 | 81 | 122 2024-01-01 | 3189 | 4097 However, upon retrieving the same query ...

Retrieve the value stored in the theme using the useState hook

Currently in the process of developing a React NextJS application integrated with MaterialUI. I have a header component that contains a switch element intended to facilitate toggling between dark and light modes within my theme file (which is a separate en ...

What kind of error should be expected in a Next.js API route handler?

Recently, I encountered an issue with my API route handler: import { NextRequest, NextResponse } from "next/server"; import dbConnect from "@/lib/dbConnect"; import User from "@/models/User"; interface ErrorMessage { mess ...

The components in Next/Image are taking their sweet time to show up

Currently in my project, I am utilizing Next.js 10.0.7 along with next-images 1.7. However, I have noticed that larger images are taking a few seconds to load onto the screen. I believe I am implementing the components correctly as you can see below, but ...

Generating an HTML version of a specific nextJS page by clicking a button that includes constantly changing data

I have a current project where I am tasked with filling a template.tsx file with the information gathered from a form, and then using that data to create an HTML file which can be downloaded to the user's device. Does anyone know how I can accomplish ...

Screen content of a post request in Node.js

Can this code in node.js + express be simplified? // Code snippet for registering a new participant app.post('/api/participant', function (req, res, next) { var data = req.body; // Ensure only specific fields are uploaded var parti ...

By enabling the "useNewUrlParser" and "useUnifiedTopology" properties to true in the MongoDB connection URL, you can prevent the need for a catch block in a promise function

Within my code, I have utilized mongoose to establish a connection with a MongoDB URL. In order to prevent the occurrence of "DeprecationWarning", I have configured parameters such as "useNewUrlParser", "useUnifiedTopology", "useFindAndModify", and "useCre ...

Encountered a problem when attempting to include a specialized heading on pages using next.js version

I'm encountering difficulties when attempting to add custom titles to my pages in my app. I am using Next.js version 13. Here is the code snippet: "use client"; export const metadata = { title: `Login - ${process.env.NEXT_PUBLIC_APP_NAME} ...

Mastering the utilization of license keys in react-froala within the Next.js framework

I am currently utilizing the "react-froala-wysiwyg": "^2.9.1-1" alongside version "next": "^7.0.2". Having obtained a license and generated a key specific to my domain, I find myself unsure of how to properly integrate it. Despite my attempts to implemen ...

Enhance your Next JS website's SEO with a combination of static pages, SSR pages, and client-side

In my project using Apollo GraphQL with Next JS, I have explored three different approaches to querying and rendering data. The first method involves Static Rendering by utilizing getStaticProps(), which looks like the following: export async function getS ...

The NextJS CSP header is causing issues for the PDFtron iframe content

Incorporating CSP headers into my project has been a recent development. Simultaneously, I have integrated the PDFTron webviewer into the project as well. The PDFTron webviewer is displayed within an iframe, and ever since adding CSP headers, I have encoun ...