Categories
JavaScript Answers

How to create document if not exists, otherwise, update and return document in either case with Node.js Mongoose?

To create document if not exists, otherwise, update and return document in either case with Node.js Mongoose, we call the findOneAndUpdate method.

For instance, we write

const query = {};
const update = { expire: new Date() };
const options = { upsert: true, new: true, setDefaultsOnInsert: true };

Model.findOneAndUpdate(query, update, options, (error, result) => {
  if (error) return;
  //...
});

to call findOneAndUpdate with the query and the update object that has the values to update in the documents.

And then the updated document are set as the value of the result parameter.

Categories
JavaScript Answers

How to fix the ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client error with Node.js?

To fix the ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client error with Node.js, we make sure we only return a response once.

For instance, we write

if (!user) {
  errors.email = "User not found";
  res.status(404).json({ errors });
  return;
}

to call res.status and json to return the 404 status and the { errors } as the response body to send the response.

Then we use return to stop running the function to make sure another response isn’t sent.

Categories
JavaScript Answers

How to run Mocha tests with extra options or parameters with JavaScript?

To run Mocha tests with extra options or parameters with JavaScript, we get the values from process.argv.

For instance, we write

const argv = require("minimist")(process.argv.slice(2));
console.log("config", argv.config);

to get the command args with process.argv in the Mocha test file.

We then parse it with the minimist library into an object and get the config config.

Then we run the test with

mocha test.js --config=VALUE
Categories
JavaScript Answers

How to inherit from the EventEmitter class with Node.js?

To inherit from the EventEmitter class with Node.js, we use the extends keyword.

For instance, we write

const EventEmitter = require("events");

class MyEmitter extends EventEmitter {
  // ...
}

const myEmitter = new MyEmitter();
myEmitter.on("event", () => {
  console.log("an event occurred!");
});
myEmitter.emit("event");

to create the MyEmitter class that inherits from the EventEmitter class.

We add our own methods inside the class.

Then we create a new instance of MyEmitter with new.

We call on to listen to the 'event' event.

And we call emit to emit the 'event' event.

Categories
JavaScript Answers

How to force Yarn to reinstall a package with JavaScript?

To force Yarn to reinstall a package with JavaScript, we delete the node_modules folder and reinstall.

To do this, we delete the node_modules folder and then run

yarn install --check-files

to reinstall all the packages.