How do I make Mongoose add createdAt and updatedAt automatically?
Pass { timestamps: true } as the second argument to new mongoose.Schema(). Mongoose will set and update both fields automatically. Use them; you will want them later for sorting and debugging.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Design a Good Mongoose Schema
Pick the right field types, add validation (required, min, max, enum, match), use defaults, index the fields you query, use refs for large N, embed small data, keep documents small, use timestamps, use enums for fixed sets, and hash sensitive fields.
Use ref for one-to-many with large N (messages, connections). Use embed for small, tightly coupled data that always loads together (an address inside a user). Embedding large or growing arrays bloats documents; use refs instead.
Index the fields you query and sort by. Unique on email. Compound on (fromUserId, toUserId) for connection requests. On (connectionId, createdAt) for messages. Do not index every field; indexes speed up reads but slow down writes.
Still have questions?
Browse all our FAQs or reach out to our support team
