Error: Document's _id field cannot be modified

I am new to both MongoDB and Backbone, and I find it challenging to grasp the concepts. My main issue revolves around manipulating attributes in Backbone.Model to efficiently use only the necessary data in Views. Specifically, I have a model:

window.User = Backbone.Model.extend({

    urlRoot:"/user",
    idAttribute: "_id",

    defaults: {
        _id: null,
        name: "",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54323b3b143635267a361e">[email protected]</a>"
    }
});

window.UserCollection = Backbone.Collection.extend({
    model: User,

    url: "user/:id"
});

Additionally, I have a View:

beforeSave: function(){
    var self = this;
    var check = this.model.validateAll();
    if (check.isValid === false) {
        utils.displayValidationErrors(check.messages);
        return false;
    }
    this.saveUser();
    return false;
},

saveUser: function(){
    var self = this;
    console.log('before save');
    this.model.save(null, {
        success: function(model){
            self.render();
            app.navigate('user/' + model.id, false);
            utils.showAlert('Success!', 'User saved successfully', 'alert-success');
        },
        error: function(){
            utils.showAlert('Error', 'An error occurred while trying to save this item', 'alert-error');
        }
    });
}

I need to utilize the 'put' method with data from any fields except '_id'. For instance, the desired format should be:

{"name": "Foo", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f1f8f8d7f5f6e5b9f5f6ed">[email protected]</a>"}

However, regardless of my actions, each request always contains:

{**"_id": "5083e4a7f4c0c4e270000001"**, "name": "Foo", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcdc4c4ebc9cad985c9cad1">[email protected]</a>"}

This leads to an error from the server:

MongoError: cannot change _id of a document old:{ _id: ObjectId('5083e4a7f4c0c4e270000001'), name: "Foo" } new:{ _id: "5083e4a7f4c0c4e270000001", name: "Bar", email: "[email protected]" }

Github link: https://github.com/pruntoff/habo

Thank you in advance!

Answer №1

After analyzing the mongo error you provided, it appears that the issue does not lie with mongo itself but rather with your attempt to change an object's _id type from ObjectId to String. This transformation is causing Mongo to encounter difficulties as it may not support this alteration.

The crucial question here is: why was the object originally assigned an id of type ObjectId? How was it initialized initially? If a different method was utilized (potentially server-side), consider setting the id type as a String to match the format expected by your script library. On the other hand, if keeping it as an ObjectId is necessary, ensure that you convert the incoming String from your script into an ObjectId before saving it in Mongo.

Hope this helps guide you in resolving the issue effectively.

Answer №2

MongoDB generates _id as an ObjectID, but doesn't return _id as an ObjectID.

Regardless of whether this inconsistency is the 'correct behavior', it can be quite a frustrating surprise for many MongoDB users.

To address this issue, you can implement the following solution:

if ( this._id && ( typeof(this._id) === 'string' ) ) {
  log('Fixing id')
  this._id = mongodb.ObjectID.createFromHexString(this._id)
}

For more information, refer to MongoDB can't update document because _id is string, not ObjectId

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

Getting data from an Ajax call

I am struggling to find a solution for retrieving data from a processing script into a Request page using Ajax and PHP. The issue I am facing is shown in the error message below: SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the J ...

Navigating with NextJS to a personalized URL and managing the feedback from an external application

I'm currently in the process of developing an application that involves redirecting users to a specific URL, prompting them to open an app (with a url starting with zel:), and then sending a request back to my server. Here's the envisioned user j ...

Is there a way to programmatically display an edit text field on an HTML page?

Currently, I have a straightforward task which involves pulling data from a MySQL database to display in an HTML table. Here is the current script: <html> <body> <table border='1'> <?php mysql_connect('url',&ap ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

What is causing the poor color and contrast of equirectangular backgrounds in Three.js, and what steps can be taken to improve them?

Using Three.js for a website project with a construction company, I created 360° photospheres using my Google Pixel 5. The client also requested a 3D representation of one of their projects, making Three.js the ideal solution. Comparison: Original photo ...

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Create a list of items with checkboxes next to each that can be repeated using PdfMake

Incorporating pdfMake into my project, I am trying to display text next to an image and replicate this section in my docDefinition. The issue arises when I attempt to repeat this part using the following code snippet: { columns: [ { ...

Tick the checkboxes that are not disabled, and leave the disabled ones unchecked

Currently, I am employing Jquery for the purpose of checking and unchecking checkboxes. However, some of these boxes are disabled, thus there is no need for them to be checked. Is there a method by which I can instruct the script to disregard disabled che ...

While attempting to retrieve cookies, an error occurs stating: "TypeError: Cannot read property 'token' of undefined"

I've successfully generated a JWT token using the following code: const jwt = require('jsonwebtoken'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const userSchema = new mongoose.Schema({ ...

Difficulty recognizing sessions in production for a self-hosted Next.js application using Clerk Dev Auth

Having trouble finding the next step in debugging as I couldn't resolve the issue on Clerk's Discord or GH Issues. It seems like it might be a Next.js problem rather than a Clerk one? I am currently running a self-hosted next.js app in a docker ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

Unable to successfully deploy Project mongodb on VPS

I am encountering an error while running my project on a VPS, however, it works fine at http://localhost:3000/. I have tried uninstalling and reinstalling npm mongodb but it does not resolve the issue. Removing require('mongodb') allows it to wo ...

Showing outcomes from various API requests

I have encountered an issue while making two API calls to a backend server and trying to display both responses in JSON format to the user. Strangely, alert 2 is showing as 'undefined' when I check the console, while alert 1 works perfectly fine. ...

mongoose fails to return posts when a *.find() method is enclosed within a function

I have successfully set up an Express REST API and I am trying to retrieve all posts when a specific route is requested from my server ("/api/posts"). When I attempt to console.log(posts), it displays the posts to me. However, when I navigate to the route ...

TinyMCE generates HTML code with embedded tags

Hey there, I'm currently facing an issue with TinyMCE that I just can't seem to solve. I've browsed through some related posts but haven't found a solution that works for me... For example: When I input something in my back office, ...

Prevent unauthorized entry to css and javascript files

Is there a way to prevent direct access to a file? I want the file to be used on my website, but I want to block it from being accessed directly. For example, if you try to open this link: https://example.com/style.css, you will see an error message. Howev ...

When using threejs, the color set for setClearColor is supposed to be white. However, when calling an external HTML file, it unexpectedly renders as

When I call an external HTML file in Three.js, the value for setClearColor is white but it renders as black. How can I solve this issue? Click here to view the image Here are the codes from the external file: <div id="3d-modal"></div> <sc ...

BufferGeometry is not being displayed

After working extensively with BufferGeometry, I considered myself quite familiar with it. However, I am currently facing an issue while trying to create a simple square plane - there is no visible plane, no errors, and everything seems to be set up correc ...

Error: Failed to decode audio content due to a DOMException that was caught in the promise

Encountering an issue with the decodeAudioData method while utilizing the Web Audio API for playback in Chrome (works seamlessly in Firefox)- Sending the audio buffer, which has been recorded by the media recorder, back from the server. Server-side wss ...

Customizing Material-ui picker: concealing text field and triggering modal with a button click

I'm currently working with version 3.2.6 of the material-ui pickers library to develop a component that has different renderings for mobile and desktop devices. For desktop, I have set up a standard inline datepicker with a text input field, while fo ...