Categories
JavaScript Answers

How to get all the values that contains part of a string using Node Mongoose find?

To get all the values that contains part of a string using Node Mongoose find, we can search with a regex.

For instance, we write

Books.find({ authors: /Alex/i }, (err, docs) => {});

to call find with an object that has authors set to the regex with the pattern we’re looking for.

And we get the results from the docs array.

We use the i flag to search in a case insensitive manner.

Categories
JavaScript Answers

How to get HTTP headers with Node.js?

To get HTTP headers with Node.js, we use the headers property.

For instance, we write

const http = require("http");
const options = { method: "HEAD", host: "example.com", port: 80, path: "/" };
const req = http.request(options, (res) => {
  console.log(JSON.stringify(res.headers));
});
req.end();

to call http.request with the options to make a get request.

And we get the response headers with res.headers in the callback.

Categories
JavaScript Answers

How to fix “ERROR: dbpath (/data/db) does not exist.” with Node MongoDB?

To fix "ERROR: dbpath (/data/db) does not exist." with Node MongoDB, we should make sure the /data/db folder exists.

To do this, we run

sudo mkdir -p /data/db/

to create the /data/db/ folder.

Then we set the current user as the owner of the folder with

sudo chown `id -u` /data/db
Categories
JavaScript Answers

How to get the latest and oldest record in Node Mongoose.js?

To get the latest and oldest record in Node Mongoose.js, we use the sort method.

For instance, we write

Tweet.findOne()
  .sort("-created_at")
  .exec((err, post) => {
    //...
  });

to call sort to sort the results by the created_at field in descending order.

Then we get the latest result from post in the callback.

Categories
JavaScript Answers

How to find Cannot find module ‘bcrypt’ error with Node?

To find Cannot find module ‘bcrypt’ error with Node, we install a few packages.

To fix this, we run

npm install node-gyp -g
npm install bcrypt -g

npm install bcrypt --save

to install node-gyp and bcrypt globally.

Then we run

npm install bcrypt --save

to install bcrypt locally.