Categories
JavaScript Answers

How to use MongoDB with promises in Node.js?

Sometimes, we want to use MongoDB with promises in Node.js.

In this article, we’ll look at how to use MongoDB with promises in Node.js.

How to use MongoDB with promises in Node.js?

To use MongoDB with promises in Node.js, we can use the MongoDB client methods with async and await.

For instance, we write

const {
  MongoClient
} = require('mongodb')

const connect = async () => {
  const url = 'mongodb://localhost:27017/example'
  const db = await MongoClient.connect(url)
  console.log(db)
}

to call MongoClient.connect with the database url to connect to the database at the given URL.

Then we get the db database connection handle with await.

await returns the resolve value from the promise returned by connect.

Conclusion

To use MongoDB with promises in Node.js, we can use the MongoDB client methods with async and await.

Categories
JavaScript Answers

How to create a basic static file server in Node.js?

Sometimes, we want to create a basic static file server in Node.js.

In this article, we’ll look at how to create a basic static file server in Node.js.

How to create a basic static file server in Node.js?

To create a basic static file server in Node.js, we can use Express.

To install it, we run

npm i express

Then we create a static file server with it by writing

const express = require('express')
const app = express()
const port = process.env.PORT || 4000;

app.use(express.static(__dirname + '/public'));
app.listen(port);

We call express.static with the folder with the static files we want to serve.

And we call app.use to use the middleware returned by express.static.

Then we call app.listen with port to start the server and listen at for traffic at the given port.

Conclusion

To create a basic static file server in Node.js, we can use Express.

Categories
JavaScript Answers

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

Sometimes, we want to create document if not exists, otherwise, update and return document in either case with Mongoose.

In this article, we’ll look at how to create document if not exists, otherwise, update and return document in either case with Mongoose.

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

To create document if not exists, otherwise, update and return document in either case with Mongoose, we can use 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, update, options and a callback.

query has the query to find the item to update.

update is an object that has the fields with the values we want to update.

options has upsert set to true to find an existing document if it exists or create a new one.

new is set to true to create a new document if it doesn’t exist.

The result parameter in the callback should have the latest document value.

Conclusion

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

Categories
JavaScript Answers

How to fix the ‘BodyParser is deprecated’ warning with Node.js and Express?

Sometimes, we want to fix the ‘BodyParser is deprecated’ warning with Node.js and Express.

In this article, we’ll look at how to fix the ‘BodyParser is deprecated’ warning with Node.js and Express.

How to fix the ‘BodyParser is deprecated’ warning with Node.js and Express?

To fix the ‘BodyParser is deprecated’ warning with Node.js and Express, we can replace bodyParser with express.urlencoded and express.json.

For instance, we write

app.use(express.urlencoded({
  extended: true
}));
app.use(express.json())

to call app.use with the middlewares returned by express.urlencoded and express.json to let us parse URL encoded and JSON request bodies.

Conclusion

To fix the ‘BodyParser is deprecated’ warning with Node.js and Express, we can replace bodyParser with express.urlencoded and express.json.

Categories
JavaScript Answers

How to fix the hostname or IP not matching certificate’s altnames with Node.js?

Sometimes, we want to fix the hostname or IP not matching certificate’s altnames with Node.js.

In this article, we’ll look at how to fix the hostname or IP not matching certificate’s altnames with Node.js.

How to fix the hostname or IP not matching certificate’s altnames with Node.js?

To fix the hostname or IP not matching certificate’s altnames with Node.js, we can use http-proxy with changeOrigin to true.

For instance, we write

const proxy = httpProxy.createProxyServer();

proxy.web(req, res, {
  changeOrigin: true,
  target: 'https://example.com:3000'
});

to create a proxy to proxy the traffic to example.com:3000.

Then we create the server with

httpProxy.createServer({
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  },
  target: 'https://example.com:3000',
  secure: true
}).listen(443);

to read the key and certificate with fs.readFileSync and then we set target to the hostname we’re hosting our server from.

Conclusion

To fix the hostname or IP not matching certificate’s altnames with Node.js, we can use http-proxy with changeOrigin to true.