Categories
JavaScript Answers

How to check if a collection exists in MongoDB native Node driver?

To check if a collection exists in MongoDB native Node driver, we call the listCollections method.

For instance we write

db.listCollections({ name: collName }).next((err, collinfo) => {
  if (collinfo) {
    // The collection exists
  }
});

to call listCollections with an object with the name property set to the collName collection name we’re looking for.

Then we call next with a callback that has the collection info set as the value of collinfo if it exists.

Categories
JavaScript Answers

How to fix Node.js cannot find module ‘mongodb’?

To fix Node.js cannot find module ‘mongodb’, we install the mongodb package.

To do this, we run

npm install mongodb 

to install the mongodb module in our project folder.

Categories
JavaScript Answers

How to bind Express to a specific IP address with Node?

To bind Express to a specific IP address with Node, we call listen with the IP address to bind to.

For instance, we write

const server = app.listen(3000, "127.0.0.1", onServerListening);

to call app.listen with the IP address to bind to as the 2nd argument to bind to 127.0.0.1.

Categories
JavaScript Answers

How to fix “Cannot GET /” error with Connect on Node.js?

To fix "Cannot GET /" error with Connect on Node.js, we use the connect.static method.

For instance, we write

const connect = require("connect");

const app = connect().use(connect.static(__dirname + "/public"));
app.listen(8180);

to call connect.static to expose the /public folder as a static files folder.

And then we call use to add the returned middleware to the app.

Then we can see the files in the folder when we go to /

Categories
JavaScript Answers

How to execute bash command in Node.js and get exit code?

To execute bash command in Node.js and get exit code, we call exec.

For instance, we write

const dir = exec("ls -la", (err, stdout, stderr) => {
  console.log(stdout);
});

dir.on("exit", (code) => {
  console.log(code);
});

to call exec to run the ls -la command.

We get the output from stdout in the callback.

Then we call dir.on to listen for the exit event.

And we get the exit code from code in the callback.