Home > Software engineering >  Add a new field for already existing resource using PUT
Add a new field for already existing resource using PUT

Time:01-25

I implemented google auth in my NextJS app. The idea is: user makes some progress working with my web app, I store this progress in local storage as an array. If he decides to register I receive the session back, then I send PUT request to db to update the document by inserting a new field (array) from local storage.

I implemented GET request that returns registered user data by email and it works. The question is, how to insert a new field using PUT method? In my case this field is array and calls progress. I'm not sure if I should use update.

This is the record from my mongodb:

_id: 63cc85641624a77f17ca5f29
name: "John P"
email: "[email protected]"
image: "https://lh3.googleusercontent.com/a/AEdFTp7xzF4eYtyhTgRxmgP4vYdCqDa6zW…"
emailVerified: null

I want to add a new field: progress: ['some data']

This is my PUT request:

      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
      

CodePudding user response:

If you want to update your document using updateOne, and add a progress key, you can use:

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