'Mongoose saves createdAt as Double not Date
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
Solution 1:[1]
Date.now() - returns a number. If you need to store a date like BSON Date object use new Date(Date.now()) instead.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kuzzy |
| Solution 2 | Mustafa Jawed |

