Timestamps not available in pre validate and pre save hooks
When we use the following option to set timestamps on $set operations, I feel that we should have these available in the pre hooks such as validate and save. Otherwise we have to add extra logic of our own which defeats the purpose of this option's intent for simplicity.
Schema.set('timestamps', {
createdAt: 'created_at',
updatedAt: 'updated_at'
});
Perhaps we add a new property to the options object, e.g. pre: true? cc @vkarpov15
I'm a little confused here, what do you mean by having these available in pre hooks?
@vkarpov15 for example:
Order.pre('save', async function(next) {
try {
const count = await lib.db.model('Orders').count({
user: this._id,
created_at: { $gte: this.created_at }, // <--- HERE
status: { $ne: 'Cancelled' }
});
this.is_first_order = count > 0;
next();
} catch (err) {
next(err);
}
});
@niftylettuce in both below cases, createdAt shows up just fine in pre save. Can you modify the below script to demonstrate your issue?
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);
const GITHUB_ISSUE = `gh7539`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;
run().then(() => console.log('done')).catch(error => console.error(error.stack));
async function run() {
await mongoose.connect(connectionString);
await mongoose.connection.dropDatabase();
const schema = new Schema({ name: String, isFirst: Boolean }, { timestamps: true });
schema.pre('save', async function() {
console.log('Pre save', this.createdAt);
const count = Order.count({
created_at: { $lte: this.created_at }
});
this.isFirst = count <= 0;
});
const Order = mongoose.model('Order', schema);
await Order.create({ name: 'test' });
const doc = await Order.findOne();
doc.name = 'foo';
await doc.save();
}
Couple suggestions:
- You don't need to call
next()in async middleware - You've got 'Order' but then you're referencing a model 'Orders', maybe you're mixing those up?
- The
is_first_ordercalculation is incorrect, you'll want to set that flag only if there's no orders whosecreated_atis$ltethe current order.
why u guys using comma please answer confused atm I mean on time tamp create

@cristhianGomez I don't understand your question, can you please clarify?
@vkarpov15 u created timestamp using comma while documentation says another syntax, When I create timestamps as documentation said It didn't work, but when i did as u did it worked.
Schema.set('timestamps', {
createdAt: 'created_at',
updatedAt: 'updated_at'
});
@cristhianGomez please clarify, I don't understand your comments. Please link to the documentation you're referring to.