mongoose: Timestamps are not being created
I’m trying to add timestamps to my nested objects, but it’s not working. Timestamps are being set only on the root documents (Church). Am I doing something wrong?
Here’s my schemas:
const churchSchema = new Schema({
churchId: {
type: Number,
required: true,
},
integration: {
type: Integration,
required: true,
},
service: {
type: Service,
required: true,
},
events: {
type: [ Event ],
required: false,
},
}, {
timestamps: true,
});
const eventSchema = new Schema({
churchId: {
type: Number,
required: true,
},
code: {
type: String,
required: true,
},
template: {
type: Template,
required: true,
},
users: {
type: [ User ],
required: false,
},
message: {
type: Message,
required: true,
},
}, {
timestamps: true,
}
const userSchema = new Schema({
churchId: {
type: Number,
required: true,
},
email: {
type: String,
required: true,
},
fullname: {
type: String,
required: true,
},
dateOfBirth: {
type: Date,
required: true,
},
contacted: {
type: Boolean,
required: true,
default: false,
},
}, {
timestamps: true,
});
Here’s the function I’m using to insert nested documents:
churchSchema.methods.addUserToEvent = async function (user, eventCode) {
return await mongoose.model('Church').findOneAndUpdate({
_id: this._id,
events: {
$elemMatch: {
code: eventCode,
users: {
$not: {
$elemMatch: {
email: user.email,
},
},
},
},
},
}, {
$addToSet: {
'events.$.users': user,
},
}, {
upsert: true,
new: true,
timestamps: true,
});
};
MongoDB: 4.4.6 Mongoose: 5.13.2 Node.js: v14.17.0
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 29
Commits related to this issue
- test(timestamps): repro #10447 — committed to Automattic/mongoose by vkarpov15 3 years ago
I did this await Wallpaper.create(data, {session}) instead of let wallpaper = new Wallpaper(data, { session }) wallpaper = await wallpaper.save() and it works for me.
Yes, you’re right! Sorry, I didn’t notice the only the first user has a timestamp.