首次接触nodejs会遇到以下问题:

module.js:340
    throw err;
         ^Error: Cannot find module 'mongodb'


解决方式如下:

After trying for some time to install it without success (since I'm new to mongo and node), I was missing the npm link step indeed. So just to summarize, I did this:

  1. npm install mongodb -g

  2. cd /path/to/my/app/folder

  3. npm link mongodb

With that in place, I could do this in my application file: require('mongodb').

Here are some references, in case you need them:

案例:

I am new to MongoDB. After spending hours of installing mongodb through npm, I finally got the picture. See, there are actually three "mongodb" you need to deal with (I am using OSX):

1. The driver used in NodeJS: That is: var mongo = require('/usr/local/lib/node_modules/mongodb'). Or, you may use "npm link" as mentioned by earlier post in order to avoid the long path. Command "npm install -g mongodb" installs the mongodb driver under /usr/local/lib (this is what "-g" means). This guy took hours and hours to install, don't know why, so be patient!

2. The mongodb utilities (i.e., the UNIX executable commands). You download them fromhttp://www.mongodb.org/downloads. It contains the mongod command that allows you to start the mongodb database. So in my /usr/local/bin, I created a symbolic link, mongod, pointing to /usr/local/lib/node_modules/mongodb-osx-x86_64-2.6.7/bin/mongod, so I can execute mongod from anywhere.

3. The mongodb database pointed by /data/db. So under /data, I created a symbolic link, db, pointing to /Users/your_user_id/Database/mongodb (or anywhere you like to put it), in which mongodb is an empty directory you may create via mkdir.

Because you have installed the #2 mongodb above, so you can execute mongod at the command line, which will create and start the database under mongodb #3.

Because you have mongodb #1 installed by npm, so now you can require it in your NodeJS program.

Job done!