Categories
JavaScript Answers

How to combine two OR-queries with AND in Mongoose and JavaScript?

To combine two OR-queries with AND in Mongoose and JavaScript, we use $and and $or together.

For instance, we write

Test.find(
  {
    $and: [{ $or: [{ a: 1 }, { b: 1 }] }, { $or: [{ c: 1 }, { d: 1 }] }],
  },
  (err, results) => {
    //...
  }
);

to call find with an object with the $and property set to an array with 2 objects with $or properties.

The 2 $or queries will then be combined with the $and query.

We get the returned results from results.

Categories
JavaScript Answers

How to wait some asynchronous tasks complete in JavaScript?

To wait some asynchronous tasks complete in JavaScript, we call the async.each method.

For instance, we write

const async = require("async");

async.each(
  ["aaa", "bbb", "ccc"],
  (name, callback) => {
    conn.collection(name).drop(callback);
  },
  (err) => {
    if (err) {
      return console.log(err);
    }
    console.log("all dropped");
  }
);

to call async.each to with an input array.

The first callback calls some async function with each item in the array.

And the 2nd callback is an error handler callback.

Categories
JavaScript Answers

How to log all queries that Mongoose fire in the application with JavaScript?

To log all queries that Mongoose fire in the application with JavaScript, we call the set method.

For instance, we write

mongoose.set("debug", (collectionName, method, query, doc) => {
  console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});

to call set with a callback to log the values from the query.

We log the collectionName collection, method that’s called, the query made, and the doc results returned.

Categories
JavaScript Answers

How to send a custom HTTP status message in Node Express?

To send a custom HTTP status message in Node Express, we call send with the message.

For instance, we write

res.status(400).send('Current password does not match');

to call send with the status message after call status to send the response with code 400.

Categories
JavaScript Answers

How to fix ‘node’ is not recognized as an internal or an external command, operable program or batch file error while using Phonegap/Cordova with JavaScript?

To fix ‘node’ is not recognized as an internal or an external command, operable program or batch file error while using Phonegap/Cordova with JavaScript, we add the Node.js executable directory to the PATH environment variable.

For instance, we run

SET PATH=C:\Program Files\Nodejs;%PATH%

to add the Node.js excutable directory to the PATH environment variable on Windows with the SET command.