What is the reason for this MongoDB document consistently having the identical nanoid?

Although I've managed to find a solution, my main concern is understanding the root cause of the bug. In the scenarios below, MongoDB documents are being created with identical id and date values respectively.

id: {
    type: String,
    required: true,
    unique: true,
    default: nanoid(),
    immutable: true,
  },
dateCreated: {
    type: Number,
    required: true,
    default: Date.now(),
    immutable: true,
  }

In contrast, in the next examples, each document has a distinct id and creation date.

id: {
    type: String,
    required: true,
    unique: true,
    default: () => nanoid(),
    immutable: true,
  },
dateCreated: {
    type: Number,
    required: true,
    default: () => Date.now(),
    immutable: true,
  }

I understand that this issue is related to value versus reference in JavaScript, but pinpointing the exact cause remains elusive to me.

Answer №1

When passing this object:

default: nanoid(),

The JavaScript interpreter will run nanoid() first and store the result in the default field.

Essentially, it is equivalent to the following:

const newId = nanoid();
...
id: {
    type: String,
    required: true,
    unique: true,
    default: newId
    immutable: true,
  },

This sets the default value to a fixed one.

Keep in mind that you can achieve the desired outcome by not including the (), like so:

id: {
    type: String,
    required: true,
    unique: true,
    default: nanoid,
    immutable: true,
  },

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

Slider-activated Pie Chart Controller

I have successfully created a pie chart using highchart and javascript, allowing me to adjust each slice individually using a slider. However, I am facing an issue where I want the maximum value of the pie to be 100%, with the other sliders contributing to ...

Search for items in Mongo using specific key-value pairs

As a beginner in Mongo, I am looking to retrieve items based on a specific key and its value. For example: { "_id" : 685, "group" : { "id" : 684, "title" : { "en" : "English title" } } } In this scenario, I ...

Leverage slot-specific information within the component's script in Vue

In my Vue project, I faced an issue where Component A has a slot that passes an object as slot-scoped to Component B: Template of Component A: <template> <div> <slot :myObject="myObject" /> </div> </template> Template of ...

Determine whether the textfield is a number or not upon losing focus

I'm seeking advice on implementing a feature using jQuery and JavaScript. I want to create a text field that, when something is inputted, will automatically add .00 at the end if it's only a number. However, if someone inputs something like 2.00, ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Explore how to effectively use multiple values in a jQuery filter function when working with data attributes

Exploring the use of jQuery filter for data attributes with tables that contain team, specialization, and level data variables. Seeking advice on the best approach and typical usage methods. Here is my HTML code: <table data-team="<?php print $name[ ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

The proper method for redirecting the view after a successful AJAX request in a MVC application

Explanation of the Issue: I have added a search function to the header section of my MVC website. It includes an input text box and a 'Search' button. The Problem at Hand: Currently, I have incorporated an AJAX function in the shared master la ...

Can a mutable static class variable be created in JavaScript?

I have an idea similar to this concept: class Example { static var X; static setX(value) { this.X = value; } static getX() { return this.X; } } This allows the variable to be stored within the class and easily modified ...

Utilize AJAX and jQuery to seamlessly submit a form

I am attempting to use jQuery and AJAX to submit a form in order to add a row to a table called cadreSante (which is in French). The code I am using for this operation is provided below. Can someone please identify any errors in the code and suggest ways t ...

Issues with grunt - Alert: Task "ngAnnotate:dist" has encountered an error. Proceed using --force option

Encountering an unexpected issue with a Grunt task that previously ran smoothly. The error message is as follows: Running "ngAnnotate:dist" (ngAnnotate) task Generating ".tmp/concat/scripts/scripts.js" from: ".tmp/concat/scripts/scripts.js"...ERROR >& ...

Adjusting Iframe Dimensions Dynamically with Javascript based on Anchor Location

I am experienced with handling this issue in flash, but I am struggling to figure out how to do it using Javascript and CSS. The problem involves an iframe that does not have an overflow property, and I need to modify its width/height. Is there a simple ...

Unprepared for handling JSON data with JavaScript and jQuery

{ "Items": [ { "location": "bakery", "item1": "milk", "item2": "bread" } ], } Currently, I am encountering difficulties in parsing a JSON object and receiving the following error: Error: Unca ...

The setInterval function continues to execute endlessly even after each interval is three months

I need to remove all expired OTP records every three months. In the file /sheduled-tasks/OTPRecords.js const prisma = require("../services/prisma"); const THREE_MONTHS = 1000 * 60 * 60 * 24 * 90; async function deleteExpiredOTPRecords() { ...

Is it possible to apply search filters within a child component in Angular?

I have a situation where I am passing data from a parent component to a child component using *ngFor / @input. The child component is created multiple times based on the number of objects in the pciData array. pciData consists of around 700 data objects, ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

Using a Vuejs web component as an input element in a non-Vue web application: A step-by-step guide

After creating a web component with VueJs using VueCli3, the compiled output appears as follows: <script src="https://unpkg.com/vue"></script> <script src="./my-lib.js"></script> <my-lib></my-lib> This particular web ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...