Reimagining the _id Attribute in MongoDB Using JavaScript Objects

In my Express project, I am conducting the following test:

  it('testing club', async () => {
    let club = await clubDAO.create(baseClubParams);

    console.log(club)
    const resp = await http.put(`/api/user/follow/${club._id}`);
    isOk(resp);
    resp.body.data.clubs.should.include(club);
    console.log(resp.body.data.clubs)

    // Re-fetch user info to verify that the change persisted
    const userResp = await http.get(`/api/user/${currentUser._id}`);
    userResp.body.data.clubs.should.include(clubId);
  });

Based on the console log, I can see that the club object is:

{
  admins: [],
  _id: 5e8b3bcb1dc53d1191a40611,
  name: 'Club Club',
  facebook_link: 'facebook',
  description: 'This is a club',
  category: 'Computer Science',
  __v: 0
}

and the clubs array is:

[
  {
    admins: [],
    _id: '5e8b3bcb1dc53d1191a40611',
    name: 'Club Club',
    facebook_link: 'facebook',
    description: 'This is a club',
    category: 'Computer Science',
    __v: 0
  }
]

The test fails at resp.body.data.clubs.should.include(club) because the _id of the club is an ObjectId and the _id of clubs[0] is a string:

AssertionError: expected [ Array(1) ] to include { admins: [],
  _id: 
   { _bsontype: 'ObjectID',
     id: <Buffer 5e 8b 3b cb 1d c5 3d 11 91 a4 06 11>,
     toHexString: [Function],
     get_inc: [Function],
     getInc: [Function],
     generate: [Function],
     toString: [Function],
     toJSON: [Function],
     equals: [Function: equals],
     getTimestamp: [Function],
     generationTime: 1586183115 },
  name: 'Club Club',
  facebook_link: 'facebook',
  description: 'This is a club',
  category: 'Computer Science',
  __v: 0 }

To address this issue, I attempted the following:

    let club = await clubDAO.create(baseClubParams);
    club._id = club._id.toString()

    console.log(club)

Unfortunately, the club id remains as an ObjectId even after this attempted fix. Can someone provide insight into why this is happening?

Answer №1

Dealing with Mongoose can be frustrating due to its handling of immutable objects. Modifying the _id directly is not allowed in this manner.

One workaround is to convert the Mongoose object to a regular object first :

club = club.toObject();
club._id = club._id.toString();

If this approach does not work, consider deep cloning your object. While not the most elegant solution, it is effective :

club = JSON.parse(JSON.stringify(club));

For more information, refer to this related question: is data returned from Mongoose immutable?

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 best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

The grid items fail to refresh even after I have made changes to the useState in my React Native application

I am currently working on a react native project that includes a grid component. My goal is to update an array in the state called selectedHomeTypes whenever a user clicks on an item within the grid. Initially, the array is set to contain only one element: ...

Issue with ng-show directive in AngularJS

Currently, I am developing a web app using AngularJS 1.6.6. In my template, I have implemented ng-show in order to recycle it: <div > <br/> <div class="form"> <form data-ng-submit="objectHandlerVM.functions.objectHandl ...

The table remains visible during an AJAX call

I need assistance with removing a table after successful deletion triggered by an AJAX to PHP call. Below is the function provided: list.php <script type="text/javascript"> function massDelete() { if (!confirm("Are you sure")) ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

Preventing Copy and Paste and Right-Click Actions With JavaScript

Similar Question: How can I prevent right-click on my webpage? Looking to prevent right-clicking and key combinations like Ctrl+V & Ctrl+C on a webpage using JavaScript. I have a form where customers need to input their details, and I want to avoid ...

Passing a deconstructed object as a parameter for a function

I'm having trouble understanding the parameter const Posts in the code snippet below. As a newcomer to node/React, I'm not sure if it's a destructured parameter object or just an object being passed as a parameter. The functions getPosts an ...

Improving the way text entered in an input box is displayed using HTML table cells

Seeking advice on how to display the last two input boxes in a dynamic HTML table so that users can easily view the data they have entered. The issue arises when the length of the data in these columns is large, making it difficult for users to see all the ...

Load website content in real-time

My website requires dynamic content to be loaded on user interaction. When a user clicks certain elements on the page, information should be retrieved from a file located in the same directory as the webpage and displayed in a designated <div>. My u ...

Click the closest checkbox when the value equals the Jquery datatable

I am facing an issue where I need to add a class and click on a specific element in each row of my jQuery datatable if a certain value is equal. However, I am unable to successfully add the class to that element and trigger a click event. <table id="us ...

Is there any specific value that will always result in a true comparison in JavaScript?

Is there a special JavaScript value that will always make a comparison true? For example using the less than operator: true < 10 true false < 10 true null < 10 true Or using the greater than operator: true > 10 ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Tips for steering clear of global variables while coding in JavaScript

What is the best way to avoid using global variables in JavaScript? //load more var totalItems = $("#myList li").size(); var startIndex = 3; $('#myList li:lt(' + startIndex + ')').show(); $('.loadmore').on('cli ...

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

How to use Python and JavaScript to make a WebElement visible in Selenium

I am currently facing an issue with uploading a PNG file using Selenium. The input element necessary for the upload process is visible to the user but not to Selenium. Following the suggestions in the Selenium FAQ, I tried using JavaScriptExecutor as shown ...

How about: "Is there a way to show items in a list without using

I have removed the bullet points from an unordered list, but I am having trouble displaying Log with every message. The code I have doesn't seem to be working as expected. I want users to be able to differentiate between messages easily, without seein ...

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

What steps can you take to resolve the issue of FirebaseError: When collection() is expected to be a CollectionReference, DocumentReference, or FirebaseFirestore?

I'm currently working on integrating Firebase with next.js, and I've encountered an error in the console that reads: FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore B ...