Node.js REST, Mongo tips

  • In express library functions: post(), get() will stop the execution of code if you write return. It’s like in any other function in programming. keyword return will always stop the function execution.
  • When you write (res is the response callback function) res.end(), res.json(), res.send(), in other words when you end the response you cannot utilize res callback again it becomes irrelevant since you completed your restful service with a response. If you have any code after res.something() it will execute till you specify a return but res will not be available anymore. If you use it however, it will throw an error.
    Refer: Execute code after res.end() (StackOverflow)
  • You don’t need to return res.end(), json(), send() if you don’t have code which needs to execute after it.
  • If you don’t have anything to send to the Frontend side then use res.end() to complete the service action.
  • Use next function, specified at the end of restful service callback function:
    .get((req, res, next) => {action}

    to catch errors and forward them to the middleware:

    if (err) {
        return next(err);
    }

    the return next() will go to the already built in error handler and will result with a 500 XHR failed request on the Frontend. Also applies for catch() blocks, having next(err) will also result with Node.js built in error handler execution giving 500.

  • A Node.js mongoose query is not a JS Promise. They just represent a async operation which returns a then so that you can apply: query().then(res=>console.log(res));
    Refer: Mongoose async queries (StackOverflow)
    If you want a real instance of JavaScript Promise then put an exec() after your “fake” Mongoose query promise: query().exec().then(res=>console.log(res));
  • The default status for res.send(), res.json() is 200 thereby no need for res.status(200).send() or res.status(200).json();
  • In Mongoose findOneAndUpdate query
    User.findOneAndUpdate(findQuery, updateData, {
       upsert:true,
       useFindAndModify:false,
       new:true
    })
    upsert:true represents that if the record doesn’t exist a new one will be created/inserted
    useFindAndModify:false removes deprecation warning
    new:true gives the response of updated data, otherwise you get the data of the current findQuery record.
    I like to specify those parameters for each query so that I know what to expect from it.
  • ObjectId(userId) vs
    new ObjectId(userId) are the same, use whichever one you like but be consistent once you pick one.
  • Do not close your mongo database connection after terminating your query and then reopen upon querying database. You should have/define a pool of connections instead and closing it in Node.js process termination
    process.on(‘SIGINT’, mongo.mongoDisconnect).on(‘SIGTERM’, mongo.mongoDisconnect);
    Refer: Closing a Mongo connection (StackOverflow)
  • Do not use query.remove() for deleting data from the database it’s obsolete, use deleteOne, deleteMany instead.
  • For clearing the session and destroying the browser cookie use:
    req.sessionOptions.maxAge = 0;
    req.session=null;
    res.clearCookie(‘cookieName’);
    res.end(); 
    (I use it to logout the user)