Home  >  Article  >  Web Front-end  >  Detailed tutorial on how to use Nodejs to connect to mongodb database

Detailed tutorial on how to use Nodejs to connect to mongodb database

巴扎黑
巴扎黑Original
2017-08-22 17:04:442204browse

This article mainly introduces the implementation code of using Nodejs to connect to the mongodb database. Friends who need it can refer to

A simple example of nodejs connecting to mongodb, from the mongodb official example

1. Create package.json

First, create our project directory connect-mongodb and use it as our current directory


mkdir connect-mongodb
cd connect-mongodb

Enter the npm init command to create package.json


npm init

Then, install the nodejs version driver of mongodb


npm install mongodb --save

The mongodb driver package will be installed into node_modules in the current directory

2. Start the MongoDB server

Install MongoDB and start the MongoDB database service. Please refer to my previous article or the official MongoDB documentation

3. Connect to MongoDB

Create an app.js file and add the following code to connect to the database named myNewDatabase on the server address 192.168.0.243 and mongodb port 27017


var MongoClient = require('mongodb').MongoClient,
  assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  db.close();
});

Enter the following command on the command line to run app.js


node app.js

4. Insert the document

in the app Add the following code to .js and use the insertMany method to add 3 documents to the documents collection


var insertDocuments = function(db, callback){
  // get ths documents collection
  var collection = db.collection('documents');
  // insert some documents
  collection.insertMany([
    {a:1},{a:2},{a:3}
  ],function(err,result){
    assert.equal(err,null);
    assert.equal(3,result.result.n);
    assert.equal(3,result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
};

The insert command returns an object containing the following properties:

  • result The document result returned by MongoDB

  • ops The document with the _id field added

  • connection used to perform the insert operation The connection

Update the following code in app.js to call the insertDocuments method


var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  db.close();
 });
});

Use node app.js to run in the command line

5. Query all documents

Add findDocuments function


var findDocuments = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // find some documents
  collection.find({}).toArray(function(err,docs){
    assert.equal(err,null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
};

findDocuments function Query all documents in all 'documents' collection and add this function to the callback function of MongoClient.connect


var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected correctly to server");
 insertDocuments(db, function() {
  findDocuments(db, function() {
   db.close();
  });
 });
});

6. Use filtering Condition (query filter) Query documents

Query documents for 'a':3


var findDocuments = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('documents');
 // Find some documents
 collection.find({'a': 3}).toArray(function(err, docs) {
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs);
  callback(docs);
 });   
}

7 . Update document


var updateDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // update document where a is 2, set b equal to 1
  collection.updateOne({a:2},{
    $set:{b:1}
  },function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("updated the document with the field a equal to 2");
    callback(result);
  });
};

The updateDocument method updates the first document that meets the condition a is 2, adds a b attribute, and sets it to 1.

Add the updateDocument method to the callback of the MongoClient.connect method


MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    updateDocument(db,function(){
      db.close();
    });
  });
});

8. Delete the document


var removeDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // remove some documents
  collection.deleteOne({a:3},function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("removed the document with the field a equal to 3");
    callback(result);
  });
};

Add to app.js


var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  updateDocument(db, function() {
   removeDocument(db, function() {
    db.close();
   });
  });
 });
});

9. Create index

Indexes can improve application performance. Below your code adds an index on the 'a' attribute


var indexCollection = function(db,callback){
  db.collection('documents').createIndex({
    a:1
  },null,function(err,results){
    console.log(results);
    callback();
  });
};

Update app.js


##

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    indexCollection(db,function(){
      db.close();
    });
  });
});

The above is the detailed content of Detailed tutorial on how to use Nodejs to connect to mongodb database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn