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

Most upvoted comments

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.

{ contacted: true, _id: 60ec836110e61f625c775103, email: ‘randal@test.com’, dateOfBirth: 2021-07-12T18:01:05.915Z }

this should have timestamps correct?

Yes, you’re right! Sorry, I didn’t notice the only the first user has a timestamp.