How to use a MongoDB password with “@” in it in Node.js?

Sometimes, we want to use a MongoDB password with “@” in it in Node.js.

In this article, we’ll look at how to use a MongoDB password with “@” in it in Node.js.

How to use a MongoDB password with “@” in it in Node.js?

To use a MongoDB password with “@” in it in Node.js, we should escape the ‘@’ by URL encoding it.

For instance, we write

mongoClient.connect("mongodb://username:p%40ssword@host:port/dbname?authSource=admin", {
  useNewUrlParser: true
}, (err, db) => {

});

to replace ‘@’ with %40 in our connecting string.

Then we set useNewUrlParser to true so that the escaped ‘@’ is converted back to ‘@’.

Conclusion

To use a MongoDB password with “@” in it in Node.js, we should escape the ‘@’ by URL encoding it.