By default, Mongoose automatically assigns the "id" property of a document to equal the document's "_id" property

I need to ensure that my Model has a unique "id" property, and I want this value to match the "_id" property of the document upon creation. Currently, my Model schema is set up like this:

const modelSchema = new Schema(
  {
    id: { type: String, unique: true },
    property_1: { type: String, unique: false }
    property_2: { type: String, unique: false }
    ...
  }
);

At the moment, I achieve this by using two separate queries - one for creating the document, and another for updating the "id" property with the value of "_id" after the document is created.

Model.create({
    propery_1: value_1,
    propery_2: value_2,
    ...
}).then((document) => {
    document.id = document._id;
    document.save();
})

Is there a way to configure my Schema to automatically set the "id" property to the value of "_id"? Alternatively, is there a method to consolidate these two queries into one while maintaining the same functionality?

Answer №1

To solve the issue, I made a simple adjustment by removing the "id" field from the Schema and creating a virtual property called "id". This allows Mongoose to automatically include the "id" field in the document. Here is the updated code snippet:

const newSchema = new Schema(
  {
    data_1: { type: String, unique: false },
    data_2: { type: String, unique: false },
    ...
  }, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
  }
);

newSchema.virtual('id', {
  id: this.id
});

Remember to include toJSON: { virtuals: true } and toObject: { virtuals: true } to ensure that the virtual fields are included in the document automatically.

Answer №2

The solution I implemented involved including a unique id property within the schema to mirror the existing _id property.

const modelSchema = new Schema(
  id: {
    type: Schema.Types.ObjectId,
    default: function () {
      return this._id;
    }
  }
);

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

Issue with req.user being Undefined in Node, Express, Passport, and Mongoose

I've encountered an issue where req.user is defined when logging in, but undefined on other paths. I'm starting to feel stuck and out of ideas at this point. Another thing is that deserialization is never being called. server.js: var LocalStra ...

Reactjs is displaying an AxiosError stating a Network Error

Working on a project with Reactjs and Nextjs, I encountered an issue where the data being posted with axios is inserting "NULL" values. I'm not sure where I am going wrong. Below is the code snippet in Nextjs: const userData = { name: state.name, ...

What is the best way to access props from a different file in a React application?

I am facing a challenge with my two files: EnhancedTableHead and OrderDialog. I need to access the props data from EnhancedTabledHead in my OrderDialog file. Is there a way to achieve this? Here is how my files are structured: //OrderDialog.jsx import ...

Encountering issues when trying to build a Vue application with Vue CLI and running npm start

I am attempting to develop an application using the **Vue CLI** command - npm create vue@latest Following the npm install, I am endeavoring to launch my app with **npm run dev** but encountering the error below. Any assistance would be greatly appreciated ...

The embedded video from YouTube refuses to appear behind other elements

I am facing an issue with YouTube embedded videos on my website. The problem is that these videos do not follow the z-index rules and are always displayed above all other elements on the page. I have tried: $('iframe','.video_container&apos ...

What is a more dynamic way to assign attributes to elements without directly embedding them in the HTML code?

For my unique scenario, my goal is to assign the attribute target = "_blank" to all <a> elements within a specific div in order to open them in new tabs. This concept could potentially be applied to any element and any attribute. I am curious if the ...

Are you looking for a Ruby on Rails guide featuring Mongoid?

I am facing an issue while following the tutorial at regarding using SQLite, but I am using Mongoid instead. Can someone please assist me? Apologies for my poor English. helper/session_helper.rb module SessionsHelper def sign_in(user) cookies.permane ...

Implement a new list field to an object using javascript

I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example: config = { existing_value: 'sample' } addToListing = (field, value, index=0) => { config = { ...confi ...

Matching current URL and links by checking the div class

How can I verify if the current URL matches a link on my page, but also check if that link has a specific div class? For example: jQuery(document).ready(function($){ // find anchor tag on page with matching current location URL jQuery("*").find("a[h ...

The hierarchy of script loading in Angular applications

After years of working with MVC, I recently delved into Angular. Although I am well-versed in JavaScript and HTML, I'm still a beginner in the world of Angular. I spent hours troubleshooting my app only to realize that the problem was elusive. The a ...

Unexpected triggering of second fail in Jquery Deferreds

Currently, I have a sequencing function that involves two REST steps - step 1 and step 2. The way I am currently handling this is by calling step1 with fail and then handlers, followed by step2 with its own fail and then handler. self.step1() .fail(se ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Truncating decimal points in JavaScript

In this scenario, if the number after the decimal point is 0, then the zero should be removed. Otherwise, the number should be displayed as it is. Here are some examples of what I am aiming for in vue: 100.023 => 100.023 1230.0 => 1230 ...

Renewing Masonry and JQuery

Currently implementing Masonry from into a project aimed at creating a timeline effect for user interaction. The goal is to automatically refresh the page at intervals (every 10 seconds during testing), but encountered an issue. Upon initial load, the ge ...

Sending property to React element to personalize Material-UI tooltip content

I am struggling to implement a unique tooltip value in MUI For more information on the Tooltip API, please visit: https://material-ui.com/api/tooltip/#css The current setup uses a slider to display integer values as tooltips, but I need to translate thes ...

Retrieving HTML content using scriptJS

Currently utilizing VueJS and encountering an issue after compiling code in production mode. I have one index.html file and several assets that are being uploaded to the cloud. The challenge lies in the fact that the client is not accepting the HTML file ...

Generating hierarchical structures from div elements

Looking for guidance on how to parse a HTML page like the one below and create a hierarchical Javascript object or JSON. Any assistance would be much appreciated. <div class="t"> <div> <div class="c"> <input t ...

"My NodeJS code is returning a string instead of JSON data when using the MongoDB populate

My current project involves managing a product with multiple providers, each having its own price. The challenge I am facing is that when using populate() to retrieve provider information by ID, it returns the data as a string instead of JSON format. Below ...

Is the Jest function, containing an asynchronous call to User.findAll [using Sequelize with PostgreSQL], failing its test?

Why is my test failing for the getAllUsers function? I suspect that the assertions are executed before all async calls to User.findAll complete. Any suggestions on how to fix this? Here is the code being tested: const { Op } = require('sequelize&apo ...

Using Javascript to delete a cookie that was created by an AJAX response

Within my Webapp (which is currently running at localhost/myApp/), I am utilizing an ajax call as shown below: $.ajax({ type: "GET", url: "http://localhost:8080/my.module/Login/login?user=abc&password=123", xhrFields: { withCredent ...