Nodejs link MongoDB database in two ways, the first is to use the official self-developed NPM package MongoDB Link, the second is the use of third-party NPM package Mongoose link;
If this is a window operating system, it is recommended to use Mongoose
First, MongoDB Link:
First install the MongoDB package in the project:
NPM Install MongoDB
After the installation is successful, create a mongodb.js file and write the code:
var mongo = require (' MongoDB '), = MONGO. Server, = MONGO. Db; var New true }); var New Db (' foo ', server);d b.open (function(err, db) { if(! ERR) { console.log ("We are connected"); });
Use node to run this JS file:
Node Mongodb.js
This is the hint we can see: We areconnected
This information is also exported in the log:
This is where we're already linked to the database.
The second kind, Mongoos link:
This is simpler and less code
or download the NPM installation package first:
NPM Install Mongoose
After the installation is successful, create a mongoose.js file and write the code:
var mongoose = require (' Mongoose '); Mongoose.connect (// database connected to a test
Here Sslpdzb is the name of the specific collection
Use node to run this JS file:
Node Mongooose.js
The results of the operation are as follows:
The log will also output a message:
Finish....
Nodejs How to MongoDB database