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

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

Prop type failure: The `actions` prop is specified as mandatory in the `Testing` component, however, its value is currently undefined

I am working on a project that involves creating a login form using React and Redux. Here's a snippet of my app.js: import React from 'react'; import { render } from 'react-dom'; import Input from 'react-toolbox/lib/input&apo ...

Accessing properties of objects using specific keys

In my coffeescript code, I am attempting to retrieve the keys from an object where the key matches a specific value. However, in addition to the object's own properties, I am also getting function properties in my result. This issue is causing an err ...

Steps for incorporating 'admin-ajax.php' on the frontend

Here is the code for Javascript. Javascript used: new AjaxUpload('#upload_btn', { action: '<?php echo admin_url("admin-ajax.php"); ?>', This function only functions when the user is logged in. ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

What is the best way to halt execution in Express.js following an error caught from an Await request?

While searching for a solution, I come across many posts that almost provide the answer I need, but nothing seems to quite work in my case. I have a function that uses asynchronous operations: const doStuff = async (data)=>{ if(data == "a bug& ...

Modify jQuery to update the background image of a data attribute when hovering over it

Something seems to be off with this topic. I am attempting to hover over a link and change the background image of a div element. The goal is to always display a different picture based on what is set in the data-rhomboid-img attribute. <div id="img- ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

Tips for modifying the color or personalizing the header arrow for the expandableRow within Mui Datatable

My MUI data table has the expandable rows option, along with an ExpandAll button in the header row. The arrow displayed in the title row is confusing for users as it's similar to the arrows in all other rows. I want to change the color of the header a ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Extract JSON data from a third-party website using JavaScript

I'm facing a challenge parsing JSON from an external website using JavaScript or jQuery for a Chrome extension. Specifically, I need to extract the number from an external URL with the JSON {"_visitor_alertsUnread":"0"} and assign that number to a var ...

Displaying Title and Description Dynamically on Markers in Angular Google Maps

I am currently utilizing Angular-google-maps, and here is the HTML code snippet: <ui-gmap-google-map center='mapData.map.center' zoom='mapData.map.zoom' events="mapEvents"> <ui-gmap-markers models="mapData.map.markers ...

Is it possible in HTML to detect *any* changes made to an input, not just those made by the keyboard?

Let's consider a scenario where we have an input element like this: <input id="myInput" type="text" /> The question now arises, how can we detect when the value of this input is changed programmatically (such as through $("#myInput").val("new ...

Unable to import the configuration module that is located three directories away in a Node.js environment

Within user.controller.js, there is a line that reads as follows: const config = require(".../config");. To provide some context, here is a visual representation of my directory structure: https://i.stack.imgur.com/dCkp1.png ...

"Unusual HTML and jQuery quirk causing a perplexing issue: a function that keeps looping inexp

A unique code written in javascript using jQuery allows users to create a "box" on a website with each click of a button, triggering an alert message upon clicking the box. The process is as follows: 1) Clicking the "Add (#addBox)" button appends a new li ...

Which is the preferred choice for navigation in a Next.js application without file routing or SSR: `next/router` or `react-router-dom`?

Our team at the company is currently utilizing Next.js for all front-end applications. We're in the process of developing a client-side application with disabled file-based routing in Next.js. Our setup involves only one single index.tsx file within t ...

What are some solutions for resolving the npm error code elifecycle issue?

After following the documentation, I successfully installed React JS but encountered an error when trying to run the app. The error code displayed was elifecycle npm err errno 1. Can someone please assist me in resolving this issue? Additionally, it's ...

What is the best way to retrieve a value in Ajax?

I'm trying to assign the result of an MVC controller method to a variable. function someFunction(){ var result; $.Ajax{ //??? } return result; } //Contrast with C++ int f() { //just! return result; } Post Script: Th ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

Adjusting image dimensions dynamically using JavaScript based on screen size

My bootstrap setup seems to be causing issues when using the @media (min-height: 1000px) rule as the image class does not respond as expected. I am looking to implement a JavaScript solution that will automatically resize images once the screen height exc ...