0
0
Expressframework~10 mins

Mongoose middleware (pre/post hooks) in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a pre-save hook that logs a message before saving a document.

Express
schema.pre('save', function(next) {
  console.log('About to save document');
  [1]();
});
Drag options to blanks, or click blank then click option'
Acallback
Bdone
Cnext
Dproceed
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to call the next function, causing the save to hang.
Calling a wrong function name like done or callback.
2fill in blank
medium

Complete the code to add a post-save hook that logs the saved document.

Express
schema.post('save', function(doc) {
  console.log('Document saved:', [1]);
});
Drag options to blanks, or click blank then click option'
Adoc
Bthis
Cdocument
DsavedDoc
Attempts:
3 left
💡 Hint
Common Mistakes
Using this instead of the passed document in post hooks.
Trying to access document properties without the argument.
3fill in blank
hard

Fix the error in the pre-remove hook to properly call the next middleware.

Express
schema.pre('remove', function([1]) {
  console.log('Removing document');
  next();
});
Drag options to blanks, or click blank then click option'
Adone
Bnext
Ccallback
Dproceed
Attempts:
3 left
💡 Hint
Common Mistakes
Not declaring the next parameter but calling next() inside the function.
Using a different parameter name but calling next().
4fill in blank
hard

Fill both blanks to create a pre-find hook that modifies the query to only find active users.

Express
schema.pre('[1]', function() {
  this.[2]({ active: true });
});
Drag options to blanks, or click blank then click option'
Afind
Bwhere
Cdelete
Dsave
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong hook name like 'save' or 'delete'.
Calling a method that does not exist on the query object.
5fill in blank
hard

Fill all three blanks to create a post-update hook that logs the update result and calls next.

Express
schema.post('[1]', function(result, [2]) {
  console.log('Update result:', [3]);
  next();
});
Drag options to blanks, or click blank then click option'
AupdateOne
Bnext
Cresult
Dsave
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong hook name like 'save'.
Swapping the order of parameters.
Not calling next() to continue middleware.