Connect to MongoDB tramite Node.js

Il test è effettuato su Centos 6.10 e con Node.js versione8.
Per l'installazione di Node.js vedere il post seguente Node.js on Centos 6.10
Per l'installazione di Mongo vedere il post seguente MongoDB on Centos 6.10

Occorre installare inoltre il driver mongodb per node.js che si chiama
npm mongodb  dove npm sta per Node Package Manager.

npm install mongodb

Successivamente creare un file js
#vi server_db1.js
-------------------------------------------------------------------------------------------------------------------

 var http = require('http');
var mongodb= require('mongodb');
var MongoClient= mongodb.MongoClient;
var MONGODB_URL='mongodb://127.0.0.1:27017';
// connect at the db before starting appplication server
MongoClient.connect(MONGODB_URL,{useNewUrlParser: true },function(err, db) {
if (err) {
 console.log(err);
 process.exit(1);
        }
        else    {
        console.log('Database connection ready');
                }
});
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('####################### Primo server web con Node.js ######################');
}).listen(3001, "0.0.0.0");
console.log('Server running at http://0.0.0.0:3001/');
-----------------------------------------------------------------------------------------------------------------------

require('mongodb') - Carica il modulo mongodb per connettersi al db mongob.
require('mongodb').MongoClient - Crea una nuova instance MongoClient.
mongoClient.connect() è un metodo per collegarsi al database MongoDB usando una connessione url.


Avviare il servizio mongod e il server web
#service mongod start

# node server_db1.js
Server running at http://0.0.0.0:3001/
Database connection ready


Esempio di connessione al database mongo db e inserimento di una collection e visualizzazione di un document tramite node.js.

#vi server_db5.js
--------------------------------------------------------------------------------------------------------------------
var mongodb= require('mongodb');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'heroesdb';
// Create a new MongoClient
//const client = new MongoClient(url,{useNewUrlParser: true });
const client = new MongoClient('mongodb://heroadmin:heroadmin@localhost:27017/heroesdb',{useNewUrlParser: true });
// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
  const db = client.db(dbName);
  insertDocuments(db, function() {
    findDocuments(db, function() {
      client.close();
    });
  });
});
// Inserisci una collaction
const insertDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('heroes');
// Insert some documents
  collection.insertMany([
  {hero:"Elektra", name:"Elektra", surname:"Natchios", groups:"Defenders"}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    assert.equal(1, result.ops.length);
    console.log("Inserted 1 documents into the collection");
    callback(result);
  });
};
// visualizza una collection
const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('heroes');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)
    callback(docs);
  });
}
--------------------------------------------------------------------------------------------------------------------------

# node server_db5.js
Server running at http://0.0.0.0:3001/
Connected successfully to server
Inserted 1 documents into the collection
Found the following records
[ { _id: 5d2352cf77b2ab5c2bc9b2b9,
    hero: 'Ironman',
    name: 'Tony',
    surname: 'Stark',
    groups: 'Avengers' },
  { _id: 5d2352cf77b2ab5c2bc9b2ba,
    hero: 'Wolverine',
    name: 'James',
    surname: 'Howlett',

    groups: [ 'Avengers', 'X-men' ] },
..........................
.......................
....................









Post popolari in questo blog

ORA-12154: TNS: il listener non è attualmente a conoscenza del servizio richiesto nel descrittore di connessione

Create e Drop Pluggable Database