0

I'm using express with mongodb to insert some goods for a store website .. is it possible to insert the current date of the inserting automatically without making any input for it

  • If you are using Mongoose then you can use timestamps https://mongoosejs.com/docs/guide.html#timestamps. – Neeraj Wadhwa Nov 30 '20 at 16:46
  • Is this what you looking for? https://stackoverflow.com/questions/37782251/auto-populate-date-in-mongodb-on-insert – vovchisko Nov 30 '20 at 16:55
  • thank you for answering me i found what i need `let dateOfCreation = new Date().toJSON().slice(0, 10).replace(/-/g, '/')` this gave me the date i want – Mohammed Q Kareem Nov 30 '20 at 17:26

1 Answers1

0

You can use mongoose timestamp which is already been present in >4 version of mongoose you can do it in this fashion

 var LoanSchema = new Schema({
  someField: { type: String, trim: true, required: true },
  someOtherField: { type: String, trim: true, required: true },
}, {
    timestamps: true
} );

It will automatically creates 2 additional fields in your collection as createdAt and updatedAt

otherwise you can add default key to your field as like this

someDateField: { type: Date, default: Date.now()},
Piyush Dubey
  • 276
  • 1
  • 13