Jader Costa
Jader Costa

Reputation: 307

Node require mongo error - 'require is not defined'

I'm having a problem with mongo and node. I have a file called db.js where I put the require('mongodb') and if I import it to my index.html, I got the error:

require is not defined

But if I go to the db.js file and use 'node db', it works. I've tried import, require, src but still nothing works. Someone could help me?

 <script type="text/javascript">
        import 'js/db.js';

const MongoClient = require('mongodb');

Upvotes: 0

Views: 1025

Answers (2)

Z_z_Z
Z_z_Z

Reputation: 1107

Is there a reason that you need to configure mongodb on the front end? Unless you have a really good reason, I would strongly recommend against that. You basically throw any notion of security right out the window by doing that.

Now that we've got that cleared up, I think what you really are asking, is how you can let users make requests to mongodb from the front end. For that, you should use fetch or an HTTP request/response library like Axios in your front end javascript. Use either of these to send requests to your node backend and then you can interact with mongodb by passing along the user-submitted data from there.

Let me know if that helps you at all or if you need more help.

Upvotes: 1

Ganesh Chowdhary
Ganesh Chowdhary

Reputation: 21

You should require mongodb statement on server side code not on the browser side.Browser don't understand the require/import statement.

You can try using module like browserify to see such functionality if it works.

http://browserify.org/

Upvotes: 0

Related Questions