Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module not found: Error: Can't resolve 'dns' when using MongoDB

I'm new to Reactjs, Nodejs and MongoDB. I'm currently trying to change Mediums snowflake tool to store users scores in a database. I have installed yarn, mongodb and mongodb-core through npm. It is a single page web application which is what I think is causing me trouble. I add

var MongoClient = require('mongodb');

To SnowflakeApp.js and encounter the following error:

Module not found: Error: Can't resolve 'dns' in '/home/mlAHO174/snowflake/node_modules/mongodb-core/lib'

I've tried googling this error and have discovered it could be a range of things. I'm not sure if it is because React is front end and I'm trying to alter back end or because mongoDB is installed incorrectly. I'm new to this so would be grateful for help!

like image 393
AlexHowell Avatar asked Sep 17 '18 14:09

AlexHowell


4 Answers

DNS is a core module of Node.JS. Telling people they need to install DNS via NPM will end up with them having a completely different module that does something else.

https://nodejs.org/api/dns.html vs https://www.npmjs.com/package/dns

This error most likely means you are trying to do something from the client-side that needs to be done on the server-side. If MongoDB module can't find the DNS component, it's running on the client-side.

MongoDB has to run on the server. In order to access data from React dynamically you'll need to set up an API using something like Express or Apollo.

Update: A great way to do this is with Azure Functions (TypeScript) or AWS (Lambda) functions

like image 131
Jason Reiche Avatar answered Oct 11 '22 18:10

Jason Reiche


The problem is that you are trying to connect to the database from the front end. If this were possible that would open up a whole world of security issues. You need to set up your database connections on the backend and then have the front end make requests to the backend to handle the database.

like image 25
Matt Avatar answered Oct 11 '22 19:10

Matt


For anyone who encounters this Error while importing the clientPromise (like in the with-mongodb template):

Make sure you're in the /pages/ directory!

It won't work in other directories like /components.

(and you should take a break or get some coffee...)

like image 35
Matthias Krämer Avatar answered Oct 11 '22 20:10

Matthias Krämer


I solved this by installing and using 'bson' instead of 'mongodb' for the client part of the code. 'bson' has a tiny bit of what 'mongodb' has and it might have what you are looking for. 'bson' is built for the browser.

In my case I needed the "ObjectId" in the browser and pulling it in from 'bson' did the trick as I didn't want to reference 'mongodb' because of the error described in the OP.

The other answers are also correct depending on why you're getting this error.

like image 20
Guy Avatar answered Oct 11 '22 19:10

Guy