REQUEST COMPLIMENTARY SQLS*PLUS LICENCE
MongoDB Node.js
The most popular database management system for Node.js at the moment is MongoDB. To work with this platform, you must first install the server MongoDB itself. More details on how to do this are described here. Besides the Mongo server itself, we need a driver to interact with Node.js.
Start working with MongoDB Node.js
When connecting and interacting with databases in MongoDB we can distinguish the following steps:
- Connecting to the server
- Getting a database object on the server
- Getting the collection object in the database
- Interaction with the collection (add, delete, receive, modify data)
So, let’s create a new project. To do this, define a new directory, which will be called mongoapp. Then let’s define a new file package.json in this directory:
{
"name": "mongoapp",
"version": "1.0.0",
"dependencies": {
"express": "^4.16.0",
"body-parser": "^1.18.0",
"mongodb": "^3.1.0"
}
}
In this case, the last dependency is “mongodb”, which represents the driver. All necessary background information on this particular driver can be found at mongodb.github.io/node-mongodb.
Then let’s go to this directory in the command line/terminal and execute the command to add all the necessary packages:
npm install
Connecting to the database
The key class for working with MongoDB is MongoClient class, and all interactions with the data warehouse will go through it. Accordingly, we must first get MongoClient:
const MongoClient = require("mongodb").MongoClient;
The connect() method is used to connect to the mongodb server:
const MongoClient = require("mongodb").MongoClient;
// create a MongoClient object and give it a connection string
const mongoClient = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true });
mongoClient.connect(function(err, client){
if(err){
return console.log(err);
}
// interaction with database
client.close();
});
At first, the MongoClient object is created. To do this, two parameters are passed to its constructor. The first parameter is the server address. As the address protocol is set “mongodb://”. On the local machine, the address is localhost, after which the port number is specified. By default, the port number is 27017.
The second pair is an optional configuration volume. MongoDb is constantly evolving. In this case, the configuration object is used, which has the property useNewUrlParser: true – it indicates to the infrastructure mongodb, that it is necessary to use a new address parcel server.
Then, a connection to the server is made using the connect method. The method accepts as a parameter the callback function which is triggered when the connection is established. This function accepts two parameters: err (an error that occurred during the connection) and client (a link to a client connected to the server).
If a connection error occurs, we can use the value err to get an error.
If there is no error, we can communicate with the server through the client object.
At the end of the database, we have to close the connection using the client.close() method.
Database, collections, and documents
Having received the object of the disabled client, we can access the database on the server. For this purpose, the method:
client.db("name_bd");
As a parameter, the name of the database we want to connect to is passed to the method.
The database in MongoDB has no tables. Instead, all data falls into collections. And within node.js, to interact with the database (add, delete, read data) we need to get the collection object. To do this, we use the db.collection method (“name_collection”), to which the name of the collection is passed.
Unlike tables in relational systems where all data is stored as rows, in MongoDB collections, data are stored as documents. For example, let us add one document to the database. For this purpose, define the following file app.js in the project directory:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });
mongoClient.connect(function(err, client){
const db = client.db("usersdb");
const collection = db.collection("users");
let user = {name: "Tom", age: 23};
collection.insertOne(user, function(err, result){
if(err){
return console.log(err);
}
console.log(result.ops);
client.close();
});
});
As a database, “usersdb” is used here. It does not matter that there is no such database on the MongoDB server by default. The server shall automatically create such a database the first time it is accessed.
Once connected, we shall access the “users” collection:
const collection = db.collection("users");
Again, it does not matter that such a collection does not exist by default in the usersdb bd, it will also be created the first time.
Once we receive the collection, we can use its methods. In this case, the insertOne() method is used to add a single document – the user object. This method has two parameters – the object to be added itself and the callback function, which is executed after adding. In this function, two parameters are used: err (an error that may occur during the operation) and result (the result of the operation is the added object).
In the callback function, the added object is inspected using the result.ops property. Moreover, it is no longer just a user object, but an object that is obtained back from the database and contains the identifier set at the time of adding.
Now, let us move on the hard disk to the directory where mongodb is installed, and in this directory, let us move to the folder bin:
Let’s run the mongodb server, which is located in this directory and which is a console program mongod.
Then we run our app.js file. As we can see, apart from the initial properties here, the document has an additional property _id, which is a unique identifier of the document that is assigned by the server when it is added.
NodeJS MongoDB Tutorial
MORE NEWS
PreambleNoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...
PreambleMongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...
5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...
The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...
PreambleMS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...
First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...
PreambleAtom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...
PreambleMongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...
FlexibilityOne of the most advertised features of MongoDB is its flexibility. Flexibility, however, is a double-edged sword. More flexibility means more...
PreambleSQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...
PreambleWriting an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...
PreambleOracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...
PreambleIBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...
What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....
PreambleIf you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...
PreambleStarting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...