Home > Blockchain >  save createdAt as timestamp in mongoose
save createdAt as timestamp in mongoose

Time:10-26

this is user model

    const mediaSchema = new mongoose.Schema({
        name: {
            required: true,
            type: string,
        },
     
    },
     { timestamps: true }
    );

mongoose saves createdAt as 2022-10-21T14:31:09.650 00:00 in data base by default .

How can I force it to save it as 201546541658323 ?

CodePudding user response:

You can not.


What you can do is disable Mongoose timestamps and create your own createdAt property that you will set to the format you want.

You can do it like this:

const mediaSchema = new mongoose.Schema({
  name: { required: true, type: string },
  createdAt: { type: Number, default: Date.now() }
});

In addition, you will have to create your logic for updatedAt property.


I don't know why you want to save it as a number, since you can easily convert the current format to the number with Date.parse() method:

Date.parse("2022-10-21T14:31:09.650 00:00"); // 201546541658323
  • Related