Trouble updating document with MongoDB updateOne when using ID as filter

I need to update a property value of a specific document by sending a request to my NextJs API using fetch.

// Update items in state when the pending time in queue has passed, set allowed: true
items.map((item) => {
  const itemDate = new Date(item.added)
  const timeDiff = currentDate.getTime() - itemDate.getTime()
  const dateDiff = timeDiff / (1000 * 3600 * 24)

  if (dateDiff >= 7) {
    
    const updateItem = async () => {
      try {
        // Data to update
        const updatedItem = {
          _id: item._id,
          name: item.name,
          price: item.price,
          allowed: true
        }
        console.log(updatedItem)

        await fetch ('/api/impulses', {
          method: 'PATCH',
          body: JSON.stringify(updatedItem)
        })
      } catch (error) {
        alert('Failed to update items status')
      }
    }

    updateItem()
  }
})

The API successfully receives the data object and I can extract all necessary information from req.body for updating the MongoDB document. However, there seems to be an issue with treating the ID (_id: ObjectId('xx1234567890xx')) for filtering the document for updating.

Despite manipulating the format and including only essential data along with the _id, I still face challenges...

const jsonData = JSON.parse(req.body)
const { _id } = jsonData

// Fields to update
const { name, price, allowed } = jsonData
const data = {
  name,
  price,
  allowed
}

const filter = {
  _id: _id
}
const update = {
  $set: data
}
const options = {
  upsert: false
}
console.log("_id: ", filter) // returns { _id: 'the-correct-id-of-this-document' }

Conclusively, the update is implemented on db.collection and responses are returned:

await db.collection('impulses').updateOne(filter, update, options)

return res.json({
  message: 'Impulse updated successfully',
  success: true
})

Even though the _id matches the document id, it doesn't update. If the option upsert: true is used, a new document is created with the same _id and updated data...

The unique aspect about the documents generated through a form submission is that the id is in this format: _id: 'xx1234567890xx'. Thus, compared to an ID with ObjectId at the start, no conflicts arise. Despite my attempts to integrate 'ObjectId' in various ways, it appears to create a new ObjectId which no longer references the original document.

Any suggestions?

Answer №1

When comparing an ObjectId object with a string using _id, it will not work as expected.

To create a proper filter object, you can do the following:

const filter = { _id: ObjectId(_id) }

Alternatively, you can use the following method:

const filter = { $expr: {$eq: [{$toString: "$_id"}, _id] } }

However, keep in mind that the second method may prevent the use of the index on _id, so it is recommended to go with the first solution.

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

Trouble accessing cookies in Next.js with getServerSideProps

I've spent hours trying to troubleshoot this issue, but I just can't seem to figure out where I'm going wrong. In my Next.JS application, I have an external REST API that I created using Express with a different address than the client. Aft ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

Efficiently scheduling file downloads using WebDriver automation

I am in the process of automating a website using WebDriver, but I have encountered unique file download requirements that differ from what is readily available online. My specific scenario involves a website where I create orders. Upon clicking the &apos ...

Identify HTML elements within a textarea or text input using JavaScript while also accommodating the common special characters ">" and "<"

Is there a way to accurately detect HTML tags in textarea or text input fields before submitting a form? While it may seem straightforward to use regular expressions like /<\/?[^>]*>/gi.test(str) for this purpose, the challenge arises when de ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

Using Cypress.env() in the sample.js file located in the fixtures folder: a comprehensive guide

In my sample.js file, the content looks like this: Cypress/fixtures/sample.js module.exports = { username: Cypress.env('username'), password: Cypress.env('password') } The configuration in Cypress.json is as follows: { "bas ...

Exploring ways to display featured posts within specific category sections

I have 2 featured posts in 1 div id, one with a big class and the other with a small class. I want the big featured div to display posts based on categories. The code for the big featured post is shown below: <div class="main_feat"> ...

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

Enhancing Your Model with Additional Details using Angular Formly

I have been utilizing Angular Formly to display forms generated from the JSON response received from services. However, I have a few inquiries. Is it feasible to retrieve data in a field (templateOptions.label, for instance) to include in the model? ...

Retrieve the height of a div element in an AngularJS framework, and assign this value to a corresponding attribute of another element

Is it possible to retrieve the height of an element using AngularJS and assign it to another div's attribute? In my Bootstrap website, I have a fixed sidebar that needs to stop before reaching the footer. To achieve this, I currently have to manually ...

Ensure menu options are aligned to the right using material-ui

My material-ui menu currently has the following setup: <span> <Link to="/issues"> <Button style={isActive(history, "/issues")}>Issues </Button> </Link> <Link to="/users"> <Button style={isActive(his ...

Is the graphql codegen accurately generating the types?

I'm in the process of developing a basic Next.js application with TypeScript by integrating Strapi as a headless CMS. The main goal is to use Strapi and GraphQL, along with TypeScript, to display content on the Next.js app. Within Strapi, there is a ...

Creating a well-structured mongoose schema for nested data representation

I am currently developing a MERN stack application and I am facing an issue with designing the mongoose schema for nested data. I need to have attributes like name, age, photo nested under year. However, I am struggling to create a dynamic schema where t ...

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

Is there a way to turn off step navigation in bootstrap?

Displayed below is a visual representation of the bootstrap step navigation component. Presently, there is an unseen 'next' button located at the bottom of the page. When this 'next' button is pressed, it transitions from 'step-1 ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

Having trouble loading select fields using AJAX within Wordpress? Update and find a solution!

UPDATE: I am struggling to iterate through the response object and populate a select field using my ajax function. Although I have tried using a for loop instead of each(), the select field gets populated with "undefined". Any suggestions on how to resolve ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

Refresh Layers in Openlayers with LayerRedraw(), Rotate Features, and Manipulate Linestring Coordinates

TLDR: I am facing difficulties with my OpenLayers map. Specifically, I want to remove and add a layer called 'track', or find a way to plot a triangle based on one set of coordinates and a heading (see below). In my OpenLayers map, there is an i ...

Can Typescript Be Integrated into an AngularJS Application?

I have been thinking about the optimal timing and scenario to implement Typescript in an AngularJS project. While I have come across examples of TS being used in a Node, Express, Mongo backend, I am particularly intrigued by how well TS integrates with A ...