Why Your Mongoose Hook is Returning 0 (The 'this' Lesson)
Building Yarncom Phase 2: Automation, Word Counts, and the "Arrow Function" Trap I’m currently on Day 2 of building Yarncom , a community-driven blogging API. Yesterday, I handled the Security Handshake. Today, I faced the Logic Layer. The goal was simple; Whenever a user saves a blog post, the API should automatically calculate the Estimated Reading Time based on a 200-words-per-minute average. Here is the technical breakdown of the challenges I faced and the code that solved them. 1. The Automation Logic (The Pre-Save Hook) Instead of forcing the user to tell us how long their post is, I used a Mongoose pre-save hook. This is a function that runs after the data is sent but before it’s persisted in the database. blogSchema.pre('save', async function() { if (this.body) { const wordsPerMinute = 200; const words = this.body.split(/\s+/).length; this.reading_time = Math.ceil(words / wordsPerMinute); console.log( Calculated: ${this.reading_time} min); } }); 2. The Trap: Arrow Functions vs.
Continue reading on Dev.to JavaScript
Opens in a new tab



