Nodejs How to MongoDB database

Source: Internet
Author: User
Tags install mongodb

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.