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

What is the process of replacing fetch with JavaScript?

Looking to test my React application and mock the backend calls, I made the decision to swap out fetch with a Jest function that returns a static value. The issue I encountered was my inability to override the default fetch behavior. After some research, ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

Just made the switch from express 3 to express 4 and now encountering an issue where req.files is showing up as

After updating from express 3 to express 4, I encountered an issue with my file upload route where req.files was returning undefined. To address this, I installed the necessary middleware as separate dependencies as they are no longer included in express. ...

Challenges with removing jwt token cookie in Express

//token creation res.cookie('jwt', token, { httpOnly: true, maxAge : 60 * 60 * 24}); //logout and destroying the token exports.logout = (req, res) => { res.cookie('jwt', "token", {httpOnly:true,maxAge:1000}) //unfo ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

MERN stack including live notification functionality

Currently, I am developing a web application that allows users to receive notifications whenever their posts receive likes. The notification feature is functional, but the issue is that the notification component only renders when the page is reloaded. I ...

Using jQuery to replace an HTML element multiple times

Seeking assistance for implementing functionality that replaces a button with an input field, where users can enter information and hit enter. Once the action is completed, the original button should reappear. The current script works effectively but lacks ...

Transforming FullCalendar (jquery) into asp.net (ashx)

///////////// Expert //////////////// $(document).ready(function() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $('#calendar').fullCalendar({ ...

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

Having trouble displaying form in a different view, form is not appearing as expected

I am facing an issue with rendering a form inside a modal. The form is being rendered but the form_for does not show up, only the inputs are visible. This prevents me from targeting the submit button, which I need for ajax functionality. My file path: Adg ...

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 ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...

Utilizing array iteration to display images

I am having trouble getting the images to display on my card component. The description appears fine, but the images are not rendering properly even though I have the image data in an array. Here is the Card Component code: export const Card = (props) =&g ...

Rendering issues arise in the app when utilizing browserHistory instead of hashHistory with React Router

I have integrated React Router into my current project in the following way: const store = Redux.createStore(bomlerApp); const App = React.createClass({ render() { return ( React.createElement('div', null, ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

The value of a select box cannot be retrieved until it has been clicked on

I am working with a selectBox element in my code: <select class="span2" name="filterYear" id="filterYear" style="margin-right:10px;"> <% for (var i = 0; i < years.length; i++) { %> <% if (years[i] == selectedYear) { %> ...

Unable to save Ajax data in session array

Currently, I am developing a cart system using jquery, ajax, and php. The issue I am facing is that the text within the HTML elements is not being added to the session array. Below is the ajax code I am using: $(document).ready(function(){ $("#car ...