Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
How can I record a timestamp of when a record is created in Mongoose schema?

I have an application that I'm building that allows users to enter records on a webpage. I want to display the date/time of when each record was submitted, I've tried several different methods and finally have the date/time to display in a format that I want, but it seems as though the timestamp is recorded when the server starts up instead of when the record is added. I'm using moment.js for formatting

Here is my schema

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");
var d = new Date();
var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a");
let codeSchema = new Schema({
    code: {
      type: String
    },
    createdAt: {
      type: String,
      default: formattedDate
    },
  },
  {
    collection: "codes"
  }
);
module.exports = mongoose.model("Code", codeSchema);

This is how the records look, except the date & time is when I start the server instead of when the document was actually added

123456789789 12-09-2021, 12:59:33 pm
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Interesting problem. I am using mongoose in an app and have not seen this issue. See schema below:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const schema = new Schema({
  createdBy: Object,
  created: { type: Date, default: Date.now },
  matchName: { type: String, required: true },
  matchType: { type: String, required: true },
  matchActive: { type: Boolean, default: false },
  matchPrivate: { type: Boolean, default: true },
  matchTime: { type: String, required: true },
  matchDate: { type: String, requried: true },
  matchPassword: String,
  matchMembers: [],
  course: Object,
  subCourse: Object,
  par: { type: Number, required: true },
  numberOfHoles: { type: Number, required: true },
  frontBackNine: { type: String, required: true, default: null },
  completed: { type: Boolean, default: false },
  compeletedOn: { type: Date },
  winner: { type: String },
  startingHole: { type: Number, default: 1 },
  scorecardSettings: { type: String, required: true },
  tournamentGroups: { type: Array, default: [] },
});

module.exports = mongoose.model("Matches", schema);

However I am not using moment.js.

Two thoughts here:

  1. try removing commenting out moment.js code and use:
Date.now

in place of the moment formatted date. This is just to see if moment is causing the issue or not and will not actual give you a solution

  1. How are you creating the collection and document? Are you creating a document when the server is started or when the user uploads the file?
about 4 years ago · Juan Pablo Isaza Relatório

0

Think about when that variable is evaluated and assigned; is when the schema is created, that happens just one time. In any case, you should assign that value at the time when you save the record, assign the value as any other.

But, moongose already has an option to assign timestamps to records when are created and updated. See it here: https://mongoosejs.com/docs/guide.html#timestamps

Your code should look like:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const codeSchema = new Schema({
    code: {
      type: String
    },
    createdAt: {
      type: String,
      default: formattedDate
    },
  },
  {
    collection: "codes",
    timestamps: true
  }
);

module.exports = mongoose.model("Code", codeSchema);

About the format, I highlight recommend take care of that after at the final point when you use the data.

about 4 years ago · Juan Pablo Isaza Relatório

0

You are assigning a predefined value, that's why it is not working, you should create a function and assign the function as a default value to get the value when the document.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");

var createdAt = function(){
    var d = new Date();
    var formattedDate = moment(d).format("MM-DD-YYYY, h:mm:ss a");
    return formattedDate;
};

let codeSchema = new Schema({
    code: {
      type: String
    },
    createdAt: {
      type: String,
      default: createdAt
    },
  },
  {
    collection: "codes"
  }
);
module.exports = mongoose.model("Code", codeSchema);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda