Home > Back-end >  How can I record a timestamp of when a record is created in Mongoose schema?
How can I record a timestamp of when a record is created in Mongoose schema?

Time:12-10

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

CodePudding user response:

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);

CodePudding user response:

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?

CodePudding user response:

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.

  • Related