ReferenceError: require is not defined in MongoDB shell

Scott Lee picture Scott Lee · Apr 30, 2015 · Viewed 10.5k times · Source

I try to connect MongoDB from Mongo client on windows command (Window 8.1). When I use require() in javascript, I have error as below. Does any one has same issue? Did I miss any require related npm installation? How can't MongoDB shell find require function?

C:\tutorial\nodeMongoAngular-master\lesson2>mongo

MongoDB shell version: 3.0.1
connecting to: test
var MongoClient = require('mongodb').MongoClient;

2015-04-30T14:33:25.812-0400 E QUERY    ReferenceError: require is not defined
    at (shell):1:19

Answer

Stennie picture Stennie · May 1, 2015

You are confusing the mongo administrative shell with the Node.js driver. While both environments happen to use JavaScript, the mongo shell has more limited I/O support and is not intended to be used as a driver for application development.

If you want to write Node.js applications using the MongoDB driver (as per your example code), you need to use the node interpreter. The Node.js driver documentation includes a Quickstart tutorial with examples that should help you get started.