If the indexed date is unchanged, the default date will remain consistent with the date the process was initiated

const saleSchema = new Schema ({
  ...
  date: {type: Date, 'default': Date.now, index: true}
 ...
})

Despite attempting to add the current date into the database using the date() function, it is consistently matching the initial indexed date and subsequent submissions also mirror this startup index.

Answer №1

If you want to automatically track the creation and modification dates of your documents in MongoDB, you can add a timestamps flag to your schema. This will ensure that each document includes a createdAt field for creation date and an updatedAt field for modification date. For example:

const mongoose = require("mongoose");

const TaskSchema = new mongoose.Schema(
  {
    task: {
      type: String,
      required: [true, "Please enter a task name"],
    },
    info: {
      type: String,
      required: [true, "Please provide details for the task"],
    },
    due: {
      type: Date,
      required: [true, "Please provide a due date"],
    },
    complete: {
      type: Boolean,
      required: true,
      default: false,
    },
    createdBy: {
      type: mongoose.Types.ObjectId,
      ref: "User",
      required: [true, "please provide user"],
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Task", TaskSchema);

By setting the timestamps flag to true in the above example, every time you retrieve a task document, it will include the creation and update timestamps as shown here:

https://i.sstatic.net/xSf6H.png

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

How can multiple elements be connected to an onclick action?

I'm having trouble figuring out how to use an onClick action with jQuery for all the elements in a list of attached files. Here is a snippet of my HTML file: <p>Attachments</p> <div> <ul id="attach"> <li id="KjG34 ...

Synchronizing two dropdown menus in Angular

I'm having trouble with binding and synchronizing select elements. I am trying to make two select elements work together, but using ng-value="$index" doesn't seem to be doing the trick. These are in sync: <select ng-model="myVar1"><op ...

Achieve this effect by making sure that when a user scrolls on their browser, 50% of the content is entered into view and the remaining 50%

Is there a way to achieve this effect? Specifically, when the user scrolls in the browser, 50% of the content is displayed at the top and the other 50% is shown at the bottom. ...

Switch up the key while iterating through a JSON object

Can you modify the key while iterating through objects using an external variable? Picture it like this: var data = [{ "id": 1, "name": "Simon", "age": 13 }, { "id": 2, "name": "Helga", "age": 18 }, { "id": 3, "name": "Tom ...

Tips for securing firebase-admin credentials in Next Js

I've encountered a challenge while using firebase-admin in Next Js. I attempted to hide the firebase service account keys using environment variables, but ran into an issue because they are not defined in server-side on Next JS. As a workaround, I had ...

What is the best way to halt all active Ajax requests initiated by a DataTables instance?

Description of Issue Every time I reset the test server to a known state, my tests fail due to ongoing Ajax requests initiated by DataTables instances. I am seeking a solution to prevent these failures by stopping the DataTables requests before resetting ...

Querying all data associated with a specific id in mongoDB

In my database, I have stored various data structures in MongoDB. When storing objects, I allowed MongoDB to generate the unique ID for me. Now, I am looking to retrieve all newly recorded or modified items starting from a specific ID. The code below hel ...

Returning data to be displayed in Jade templates, leveraging Express and Node.js

Yesterday, I had a question. Instead of using next() and passing an Error object, I decided to figure out what it was doing and replicate it. So now, when someone logs in and it fails, I handle it like this: res.render("pages/home", { ...

Can PHP and SQL Server be vulnerable to SQL injection attacks?

Validation plays a crucial role in PHP to prevent client-side or external injections. I'm curious about the possibility of injection occurring after PHP has prepared and executed the query, but before it reaches the database. Does this risk increase ...

Creating Sliding Panels: A Step-by-Step Guide

I am new to JavaScript and jQuery, and I am looking to create a panel system similar to Spotify's design. Here is a description of what I am trying to achieve: When a user clicks on an artist or song/album on Spotify, a panel slides in from the righ ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Analyzing input from the user for string comparison

I am trying to create a code that activates when the user inputs a specific symbol or string. The issue is that it seems to be disregarding the if statements I have implemented. Here is the challenge at hand: Develop a program that can determine the colo ...

The optimal method for designing a select menu to ensure it works smoothly on various web browsers

Recently, I encountered an issue with customizing a select menu using CSS and jQuery. After some work, I was able to achieve a result that I am quite pleased with: So far, the styling works perfectly in Mozilla, Opera, Chrome, and IE7+. Below is the curr ...

Node Express functioned as a pushState-enabled server, capable of serving any static resource without the need for a path

I am in the process of creating a one-page web application using either Ember.js or Backbone.js for the front end MVC, and express.js (node.js) as the back end server. server/app.js code snippet: app.use(bodyParser.json()); app.use(express.static(path.j ...

Update a BehaviourSubject's value using an Observable

Exploring options for improving this code: This is currently how I handle the observable data: this.observable$.pipe(take(1)).subscribe((observableValue) => { this.behaviourSubject$.next(observableValue); }); When I say improve, I mean finding a wa ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Unable to successfully change the Span Class

My webpage has the code snippet below, but it's not functioning as expected. I have tried two methods to change the span's class attribute, but they aren't working. Could someone please help me identify where the issue lies? :) <script l ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...