I want mongoose to save createdAt
field as Date object not Double. please help.
this is my schema
const allSchema = new mongoose.Schema({ any: {} }, {
safe: false,
strict: false,
versionKey: false,
bufferCommands: false,
validateBeforeSave: false,
timestamps: { createdAt: 'createdAt', updatedAt: 'updated_at' },
});
This is how i am using it. I am setting the createdAt
using javascript Date object. But it is saved as Double. I need it to be saved as Date to be able to use the TTL index on those documents to expire them after X seconds.
const con = mongoose.createConnection(uri, opts);
const model = con.model('allSchema', allSchema, collectionName, true);
model.then(async (m) => {
// here
fields.createdAt = Date.now();
// check if we have fields as objects need to be stringify before insert
Object.keys(fields).forEach((key) => {
const val = fields[key] || '';
if (typeof val === 'object') {
fields[key] = JSON.stringify(val).toString();
}
});
return m.collection.insertOne(fields);
});
Thank you in advance
2
Answers
Instead using created_at and updated_at in timestamp use:
toJSON: { virtuals: true }, timestamps: true
This will automatically add created_at and updated_at fields.
Date.now()
– returns a number. If you need to store a date like BSON Date object usenew Date(Date.now())
instead.