Book Part3 - NodeJS
Book Part3 - NodeJS
js
Introduction
What is Node.js?
Node.js is an open source server environment
Node.js is free
Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
Node.js uses JavaScript on the server
Why Node.js?
Node.js uses asynchronous programming!
A common task for a web server can be to open a file on the server and return the
content to the client.
Node.js eliminates the waiting, and simply continues with the next request.
Download Node.js
The official Node.js website has installation instructions for
Node.js: https://nodejs.org
Getting Started
Once you have downloaded and installed Node.js on your computer, let's try to
display "Hello World" in a web browser.
Create a Node.js file named "myfirst.js", and add the following code:
myfirst.js
The code tells the computer to write "Hello World!" if anyone (e.g. a web browser)
tries to access your computer on port 8080.
How to open the command line interface on your computer depends on the
operating system. For Windows users, press the start button and look for
"Command Prompt", or simply write "cmd" in the search field.
Navigate to the folder that contains the file "myfirst.js", the command line
interface window should look something like this:
C:\Users\Your Name>_
Start your command line interface, write node myfirst.js and hit enter:
Initiate "myfirst.js":
If anyone tries to access your computer on port 8080, they will get a "Hello
World!" message in return!
Node.js Modules
What is a Module in Node.js?
Consider modules to be the same as JavaScript libraries.
Built-in Modules
Node.js has a set of built-in modules which you can use without any further
installation.
Include Modules
To include a module, use the require() function with the name of the module:
The following example creates a module that returns a date and time object:
Example
Create a module that returns the current date and time:
exports.myDateTime = function () {
return Date();
};
Use the exports keyword to make properties and methods available outside the
module file.
Example
Use the module "myfirstmodule" in a Node.js file:
Notice that we use ./ to locate the module, that means that the module is located
in the same folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
If you have followed the same steps on your computer, you will see the same
result as the example: http://localhost:8080
Example
var http = require('http');
The function passed into the http.createServer() method, will be executed when
someone tries to access the computer on port 8080.
Save the code above in a file called "demo_http.js", and initiate the file:
Initiate demo_http.js:
Example
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
The first argument of the res.writeHead() method is the status code, 200 means
that all is OK, the second argument is an object containing the response headers.
This object has a property called "url" which holds the part of the url that comes
after the domain name:
demo_http_url.js
Save the code above in a file called "demo_http_url.js" and initiate the file:
Initiate demo_http_url.js:
If you have followed the same steps on your computer, you should see two
different results when opening these two addresses:
http://localhost:8080/summer
/summer
http://localhost:8080/winter
/winter
Example
Split the query string into readable parts:
Save the code above in a file called "demo_querystring.js" and initiate the file:
Initiate demo_querystring.js:
The address:
http://localhost:8080/?year=2017&month=July
2017 July
Node.js File System Module
Node.js as a File Server
The Node.js file system module allows you to work with the file system on your
computer.
var fs = require('fs');
Read files
Create files
Update files
Delete files
Rename files
Read Files
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Save the code above in a file called "demo_readfile.js", and initiate the file:
Initiate demo_readfile.js:
If you have followed the same steps on your computer, you will see the same
result as the example: http://localhost:8080
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile() method appends specified content to a file. If the file does not
exist, the file will be created:
Example
Create a new file using the appendFile() method:
var fs = require('fs');
The fs.open() method takes a "flag" as the second argument, if the flag is "w" for
"writing", the specified file is opened for writing. If the file does not exist, an
empty file is created:
Example
Create a new, empty file using the open() method:
var fs = require('fs');
The fs.writeFile() method replaces the specified file and content if it exists. If the
file does not exist, a new file, containing the specified content, will be created:
Example
Create a new file using the writeFile() method:
var fs = require('fs');
Update Files
The File System module has methods for updating files:
fs.appendFile()
fs.writeFile()
The fs.appendFile() method appends the specified content at the end of the
specified file:
Example
Append "This is my text." to the end of the file "mynewfile1.txt":
var fs = require('fs');
Example
Replace the content of the file "mynewfile3.txt":
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Delete Files
To delete a file with the File System module, use the fs.unlink() method.
Example
Delete "mynewfile2.txt":
var fs = require('fs');
Rename Files
To rename a file with the File System module, use the fs.rename() method.
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
Parse an address with the url.parse() method, and it will return a URL object with
each part of the address as properties:
Example
Split a web address into readable parts:
summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
Create a Node.js file that opens the requested file and returns the content to the
client. If anything goes wrong, throw a 404 error:
demo_fileserver.js:
Initiate demo_fileserver.js:
If you have followed the same steps on your computer, you should see two
different results when opening these two addresses:
http://localhost:8080/summer.html
Summer
I love the sun!
http://localhost:8080/winter.html
Winter
I love the snow!
Node.js NPM
What is NPM?
NPM is a package manager for Node.js packages, or modules if you like.
The NPM program is installed on your computer when you install Node.js
What is a Package?
A package in Node.js contains all the files you need for a module.
Download a Package
Downloading a package is very easy.
Open the command line interface and tell NPM to download the package you want.
Download "upper-case":
NPM creates a folder named "node_modules", where the package will be placed.
All packages you install in the future will be placed in this folder.
C:\Users\My Name\node_modules\upper-case
Using a Package
Once the package is installed, it is ready to use.
Include the "upper-case" package the same way you include any other module:
var uc = require('upper-case');
Create a Node.js file that will convert the output "Hello World!" into upper-case
letters:
Example
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Save the code above in a file called "demo_uppercase.js", and initiate the file:
Initiate demo_uppercase:
If you have followed the same steps on your computer, you will see the same
result as the example: http://localhost:8080
Node.js MySQL
Node.js can be used in database applications.
MySQL Database
To be able to experiment with the code examples, you should have MySQL
installed on your computer.
To access a MySQL database with Node.js, you need a MySQL driver. This tutorial
will use the "mysql" module, downloaded from NPM.
To download and install the "mysql" module, open the Command Terminal and
execute the following:
Create Connection
Start by creating a connection to the database.
demo_db_connection.js
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Save the code above in a file called "demo_db_connection.js" and run the file:
Run "demo_db_connection.js"
Connected!
Now you can start querying the database using SQL statements.
Query a Database
Use SQL statements to read from (or write to) a MySQL database. This is also
called "to query" the database.
The connection object created in the example above, has a method for querying
the database:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
The query method takes an sql statements as a parameter and returns the result.
Example
Create a database named "mydb":
Save the code above in a file called "demo_create_db.js" and run the file:
Run "demo_create_db.js"
Connected!
Database created
Make sure you define the name of the database when you create the connection:
Example
Create a table named "customers":
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Save the code above in a file called "demo_create_table.js" and run the file:
Run "demo_create_table.js"
Connected!
Table created
Primary Key
When creating a table, you should also create a column with a unique key for each
record.
Example
Create primary key when creating the table:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Example
Create primary key on an existing table:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY
KEY";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table altered");
});
});
Example
Insert a record in the "customers" table:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc',
'Highway 37')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
Save the code above in a file called "demo_db_insert.js", and run the file:
Run "demo_db_insert.js"
Connected!
1 record inserted
Example
Fill the "customers" table with data:
Save the code above in a file called "demo_db_insert_multple.js", and run the file:
Run "demo_db_insert_multiple.js"
Connected!
Number of records inserted: 14
The result object contains information about how the query affected the table.
The result object returned from the example above looks like this:
{
fieldCount: 0,
affectedRows: 14,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '\'Records:14 Duplicated: 0 Warnings: 0',
protocol41: true,
changedRows: 0
}
Example
Return the number of affected rows:
console.log(result.affectedRows)
14
Get Inserted ID
For tables with an auto increment id field, you can get the id of the row you just
inserted by asking the result object.
Note: To be able to get the inserted id, only one row can be inserted.
Example
Insert a record in the "customers" table, and return the ID:
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO customers (name, address) VALUES ('Michelle', 'Blue
Village 1')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, ID: " + result.insertId);
});
});
Save the code above in a file called "demo_db_insert_id.js", and run the file:
Run "demo_db_insert_id.js"
Example
Select all records from the "customers" table, and display the result object:
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Run "demo_db_select.js"
[
{ id: 1, name: 'John', address: 'Highway 71'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'},
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 9, name: 'Susan', address: 'One way 98'},
{ id: 10, name: 'Vicky', address: 'Yellow Garden 2'},
{ id: 11, name: 'Ben', address: 'Park Lane 38'},
{ id: 12, name: 'William', address: 'Central st 954'},
{ id: 13, name: 'Chuck', address: 'Main Road 989'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'}
]
Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement
followed by the column name.
Example
Select name and address from the "customers" table, and display the return
object:
con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM customers", function (err, result,
fields) {
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_select2.js" and run the file:
Run "demo_db_select2.js"
[
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
{ name: 'Richard', address: 'Sky st 331'},
{ name: 'Susan', address: 'One way 98'},
{ name: 'Vicky', address: 'Yellow Garden 2'},
{ name: 'Ben', address: 'Park Lane 38'},
{ name: 'William', address: 'Central st 954'},
{ name: 'Chuck', address: 'Main Road 989'},
{ name: 'Viola', address: 'Sideway 1633'}
]
To return e.g. the address of the third record, just refer to the third array object's
address property:
Example
Return the address of the third record:
console.log(result[2].address);
Example
Select all records from the "customers" table, and display the fields object:
con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM
customers", function (err, result, fields) {
if (err) throw err;
console.log(fields);
});
});
Save the code above in a file called "demo_db_select_fields.js" and run the file:
Run "demo_db_select_fields.js"
[
{
catalog: 'def',
db: 'mydb',
table: 'customers',
orgTable: 'customers',
name: 'name',
orgName: 'name',
charsetNr: 33,
length: 765,
type: 253,
flags: 0,
decimals: 0,
default: undefined,
zeroFill: false,
protocol41: true
},
{
catalog: 'def',
db: 'mydb',
table: 'customers',
orgTable: 'customers',
name: 'address',
orgName: 'address',
charsetNr: 33,
length: 765,
type: 253,
flags: 0,
decimals: 0,
default: undefined,
zeroFill: false,
protocol41: true
}
]
As you can see from the result of the example above, the fields object is an array
containing information about each field as an object.
To return e.g. the name of the second field, just refer to the second array item's
name property:
Example
Return the name of the second field:
console.log(fields[1].name);
address
Node.js MySQL Where
Select With a Filter
When selecting records from a table, you can filter the selection by using the
"WHERE" statement:
Example
Select record(s) with the address "Park Lane 38":
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address = 'Park Lane
38'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_where.js" and run the file:
Run "demo_db_where.js"
[
{ id: 11, name: 'Ben', address: 'Park Lane 38'}
]
Wildcard Characters
You can also select the records that starts, includes, or ends with a given letter or
phrase.
Use the '%' wildcard to represent zero, one or multiple characters:
Example
Select records where the address starts with the letter 'S':
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address LIKE
'S%'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_where_s.js" and run the file:
Run "demo_db_where_s.js"
[
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'}
]
You can also use a ? as a placeholder for the values you want to escape.
In this case, the variable is sent as the second parameter in the query() method:
Example
Escape query values by using the placeholder ? method:
If you have multiple placeholders, the array contains multiple values, in that
order:
Example
Multiple placeholders:
The ORDER BY keyword sorts the result ascending by default. To sort the result in
descending order, use the DESC keyword.
Example
Sort the result alphabetically by name:
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers ORDER BY name", function (err, result)
{
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_orderby.js" and run the file:
Run "demo_db_orderby.js"
[
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 11, name: 'Ben', address: 'Park Lane 38'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'},
{ id: 13, name: 'Chuck', address: 'Main Road 989'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 1, name: 'John', address: 'Higheay 71'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 9, name: 'Susan', address: 'One way 98'},
{ id: 10, name: 'Vicky', address: 'Yellow Garden 2'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'},
{ id: 12, name: 'William', address: 'Central st 954'}
]
ORDER BY DESC
Use the DESC keyword to sort the result in a descending order.
Example
Sort the result reverse alphabetically by name:
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers ORDER BY name DESC", function (err,
result) {
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_orderby_desc.js" and run the file:
Run "demo_db_orderby_desc.js"
Example
Delete any record with the address "Mountain 21":
con.connect(function(err) {
if (err) throw err;
var sql = "DELETE FROM customers WHERE address = 'Mountain 21'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies
which record or records that should be deleted. If you omit the WHERE clause, all
records will be deleted!
Save the code above in a file called "demo_db_delete.js" and run the file:
Run "demo_db_delete.js"
The result object contains information about how the query affected the table.
The result object returned from the example above looks like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
Example
Return the number of affected rows:
console.log(result.affectedRows)
1
Node.js MySQL Drop Table
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
Example
Delete the table "customers":
con.connect(function(err) {
if (err) throw err;
var sql = "DROP TABLE customers";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table deleted");
});
});
Save the code above in a file called "demo_db_drop_table.js" and run the file:
Run "demo_db_drop_table.js"
Table deleted
con.connect(function(err) {
if (err) throw err;
var sql = "DROP TABLE IF EXISTS customers";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_drop_table_if.js" and run the file:
Run "demo_db_drop_table_if.js"
If the table exist, the result object will look like this:
{
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverstatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
If the table does not exist, the result object will look like this:
{
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverstatus: 2,
warningCount: 1,
message: '',
protocol41: true,
changedRows: 0
}
As you can see the only differnce is that the warningCount property is set to 1 if
the table does not exist.
Example
Overwrite the address column from "Valley 345" to "Canyon 123":
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address =
'Valley 345'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies
which record or records that should be updated. If you omit the WHERE clause, all
records will be updated!
Save the code above in a file called "demo_db_update.js" and run the file:
Run "demo_db_update.js"
1 record(s) updated
The result object contains information about how the query affected the table.
The result object returned from the example above looks like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1
}
Example
Return the number of affected rows:
console.log(result.affectedRows)
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers LIMIT 5";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
Save the code above in a file called "demo_db_limit.js" and run the file:
Run "demo_db_limit.js"
[
{ id: 1, name: 'John', address: 'Highway 71'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'}
]
Example
Start from position 3, and return the next 5 records:
var mysql = require('mysql');
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers LIMIT 5 OFFSET 2";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
Note: "OFFSET 2", means starting from the third position, not the second!
Save the code above in a file called "demo_db_offset.js" and run the file:
Run "demo_db_offset.js"
[
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'}
]
Shorter Syntax
You can also write your SQL statement like this "LIMIT 2, 5" which returns the
same as the offset example above:
Example
Start from position 3, and return the next 5 records:
var mysql = require('mysql');
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers LIMIT 2, 5";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
Note: The numbers are reversed: "LIMIT 2, 5" is the same as "LIMIT 5 OFFSET 2"
Node.js MongoDB
Node.js can be used in database applications.
MongoDB
To be able to experiment with the code examples, you will need access to a
MongoDB database.
To download and install the official MongoDB driver, open the Command Terminal
and execute the following:
Download and install mongodb package:
MongoDB will create the database if it does not exist, and make a connection to it.
Example
Create a database called "mydb":
Save the code above in a file called "demo_create_mongo_db.js" and run the file:
Run "demo_create_mongo_db.js"
Database created!
Creating a Collection
To create a collection in MongoDB, use the createCollection() method:
Example
Create a collection called "customers":
Run "demo_mongodb_createcollection.js"
Collection created!
MongoDB waits until you have inserted a document before it actually creates the
collection.
Node.js MongoDB Insert
Insert Into Collection
To insert a record, or document as it is called in MongoDB, into a collection, we
use the insertOne() method.
The first parameter of the insertOne() method is an object containing the name(s)
and value(s) of each field in the document you want to insert.
It also takes a callback function where you can work with any errors, or the result
of the insertion:
Example
Insert a document in the "customers" collection:
Save the code above in a file called "demo_mongodb_insert.js" and run the file:
Run "demo_mongodb_insert.js"
1 document inserted
Note: If you try to insert documents in a collection that do not exist, MongoDB
will create the collection automatically.
Insert Multiple Documents
To insert multiple documents into a collection in MongoDB, we use
the insertMany() method.
It also takes a callback function where you can work with any errors, or the result
of the insertion:
Example
Insert multiple documents in the "customers" collection:
The result object contains information about how the insertion affected the
database.
The object returned from the example above looked like this:
{
result: { ok: 1, n: 14 },
ops: [
{ name: 'John', address: 'Highway 71', _id: 58fdbf5c0ef8a50b4cdd9a84 },
{ name: 'Peter', address: 'Lowstreet 4', _id: 58fdbf5c0ef8a50b4cdd9a85 },
{ name: 'Amy', address: 'Apple st 652', _id: 58fdbf5c0ef8a50b4cdd9a86 },
{ name: 'Hannah', address: 'Mountain 21', _id: 58fdbf5c0ef8a50b4cdd9a87 },
{ name: 'Michael', address: 'Valley 345', _id: 58fdbf5c0ef8a50b4cdd9a88 },
{ name: 'Sandy', address: 'Ocean blvd 2', _id: 58fdbf5c0ef8a50b4cdd9a89 },
{ name: 'Betty', address: 'Green Grass 1', _id: 58fdbf5c0ef8a50b4cdd9a8a},
{ name: 'Richard', address: 'Sky st 331', _id: 58fdbf5c0ef8a50b4cdd9a8b },
{ name: 'Susan', address: 'One way 98', _id: 58fdbf5c0ef8a50b4cdd9a8c },
{ name:'Vicky', address:'Yellow Garden 2', _id: 58fdbf5c0ef8a50b4cdd9a8d},
{ name: 'Ben', address: 'Park Lane 38', _id: 58fdbf5c0ef8a50b4cdd9a8e },
{ name:'William', address:'Central st 954', _id:58fdbf5c0ef8a50b4cdd9a8f},
{ name:'Chuck', address: 'Main Road 989', _id: 58fdbf5c0ef8a50b4cdd9a90 },
{ name:'Viola', address: 'Sideway 1633', _id: 58fdbf5c0ef8a50b4cdd9a91 }
],
insertedCount: 14,
insertedIds: [
58fdbf5c0ef8a50b4cdd9a84,
58fdbf5c0ef8a50b4cdd9a85,
58fdbf5c0ef8a50b4cdd9a86,
58fdbf5c0ef8a50b4cdd9a87,
58fdbf5c0ef8a50b4cdd9a88,
58fdbf5c0ef8a50b4cdd9a89,
58fdbf5c0ef8a50b4cdd9a8a,
58fdbf5c0ef8a50b4cdd9a8b,
58fdbf5c0ef8a50b4cdd9a8c,
58fdbf5c0ef8a50b4cdd9a8d,
58fdbf5c0ef8a50b4cdd9a8e,
58fdbf5c0ef8a50b4cdd9a8f
58fdbf5c0ef8a50b4cdd9a90,
58fdbf5c0ef8a50b4cdd9a91 ]
}
Example
Return the number of inserted documents:
console.log(res.insertedCount)
14
In the example above no _id field was specified, and as you can see from the
result object, MongoDB assigned a unique _id for each document.
If you do specify the _id field, the value must be unique for each document:
Example
Insert three records in a "products" table, with specified _id fields:
Save the code above in a file called "demo_mongodb_insert_id.js" and run the
file:
Run "demo_mongodb_insert_id.js"
{
result: { ok: 1, n: 3 },
ops: [
{ _id: 154, name: 'Chocolate Heaven },
{ _id: 155, name: 'Tasty Lemon },
{ _id: 156, name: 'Vanilla Dream } ],
insertedCount: 3,
insertedIds: [
154,
155,
156 ]
}
Just like the SELECT statement is used to find data in a table in a MySQL
database.
Find One
To select data from a collection in MongoDB, we can use the findOne() method.
The first parameter of the findOne() method is a query object. In this example we
use an empty query object, which selects all documents in a collection (but
returns only the first document).
Example
Find the first document in the customers collection:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
Save the code above in a file called "demo_mongodb_findone.js" and run the file:
Run "demo_mongodb_findone.js"
Company Inc.
Find All
To select data from a table in MongoDB, we can also use the find() method.
The first parameter of the find() method is a query object. In this example we use
an empty query object, which selects all documents in the collection.
No parameters in the find() method gives you the same result as SELECT * in
MySQL.
Example
Find all documents in the customers collection:
Save the code above in a file called "demo_mongodb_find.js" and run the file:
Run "demo_mongodb_find.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain 21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a , name: 'Betty', address: 'Green Grass 1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st 331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d , name:'Vicky', address:'Yellow Garden 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'},
{ _id:58fdbf5c0ef8a50b4cdd9a8f , name:'William', address:'Central st 954'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: 'Main Road 989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway 1633'}
]
Find Some
The second parameter of the find() method is the projection object that describes
which fields to include in the result.
This parameter is optional, and if omitted, all fields will be included in the result.
Example
Return the fields "name" and "address" of all documents in the customers
collection:
Save the code above in a file called "demo_mongodb_find_fields.js" and run the
file:
Run "demo_mongodb_find_fields.js"
[
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
{ name: 'Richard', address: 'Sky st 331'},
{ name: 'Susan', address: 'One way 98'},
{ name: 'Vicky', address: 'Yellow Garden 2'},
{ name: 'Ben', address: 'Park Lane 38'},
{ name: 'William', address: 'Central st 954'},
{ name: 'Chuck', address: 'Main Road 989'},
{ name: 'Viola', address: 'Sideway 1633'}
]
You are not allowed to specify both 0 and 1 values in the same object (except if
one of the fields is the _id field). If you specify a field with the value 0, all other
fields get the value 1, and vice versa:
Example
This example will exclude "address" from the result:
Example
This example will return only the "name" field:
Example
This example will give you the same result as the first example; return all fields
except the _id field:
To return e.g. the address of the third document, just refer to the third array
object's address property:
Example
Return the address of the third document:
console.log(result[2].address);
Apple st 652
Example
Find documents with the address "Park Lane 38":
Save the code above in a file called "demo_mongodb_query.js" and run the file:
Run "demo_mongodb_query.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38' }
]
To find only the documents where the "address" field starts with the letter "S", use
the regular expression /^S/:
Example
Find documents where the address starts with the letter "S":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
Save the code above in a file called "demo_mongodb_query_s.js" and run the file:
Run "demo_mongodb_query_s.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st 331' },
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway 1633' }
]
The sort() method takes one parameter, an object defining the sorting order.
Example
Sort the result alphabetically by name:
Save the code above in a file called "demo_sort.js" and run the file:
Run "demo_sort.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a, name: 'Betty', address: 'Green Grass 1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: 'Main Road 989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: 'Mountain 21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley 345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', address: 'Sky st 331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d, name:'Vicky', address:'Yellow Garden 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway 1633'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8f, name:'William', address:'Central st 954'}
]
Sort Descending
Use the value -1 in the sort object to sort descending.
{ name: 1 } // ascending
{ name: -1 } // descending
Example
Sort the result reverse alphabetically by name:
Save the code above in a file called "demo_sort_desc.js" and run the file:
Run "demo_sort_desc.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a8f, name:'William', address:'Central st 954'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway 1633'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address:'Yellow Garden 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', address: 'Sky st 331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley 345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: 'Mountain 21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: 'Main Road 989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a, name: 'Betty', address: 'Green Grass 1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', address: 'Apple st 652'}
]
The first parameter of the deleteOne() method is a query object defining which
document to delete.
Note: If the query finds more than one document, only the first occurrence is
deleted.
Example
Delete the document with the address "Mountain 21":
Save the code above in a file called "demo_delete.js" and run the file:
Run "demo_delete.js"
1 document deleted
Delete Many
To delete more than one document, use the deleteMany() method.
The first parameter of the deleteMany() method is a query object defining which
documents to delete.
Example
Delete all documents were the address starts with the letter "O":
Save the code above in a file called "demo_delete_many.js" and run the file:
Run "demo_delete_many.js"
2 document(s) deleted
Most of the information is not important to understand, but one object inside the
object is called "result" which tells us if the execution went OK, and how many
documents were affected.
{ n: 2, ok: 1 }
You can use this object to return the number of deleted documents:
Example
Return the number of deleted documents:
console.log(obj.result.n);
2
Node.js MongoDB Drop
Drop Collection
You can delete a table, or collection as it is called in MongoDB, by using
the drop() method.
The drop() method takes a callback function containing the error object and the
result parameter which returns true if the collection was dropped successfully,
otherwise it returns false.
Example
Delete the "customers" table:
Save the code above in a file called "demo_drop.js" and run the file:
Run "demo_drop.js"
Collection deleted
db.dropCollection
You can also use the dropCollection() method to delete a table (collection).
The dropCollection() method takes two parameters: the name of the collection and
a callback function.
Example
Delete the "customers" collection, using dropCollection():
Save the code above in a file called "demo_dropcollection.js" and run the file:
Run "demo_dropcollection.js"
Collection deleted
The first parameter of the updateOne() method is a query object defining which
document to update.
Note: If the query finds more than one record, only the first occurrence is
updated.
The second parameter is an object defining the new values of the document.
Example
Update the document with the address "Valley 345" to name="Mickey" and
address="Canyon 123":
Save the code above in a file called "demo_update_one.js" and run the file:
Run "demo_update_one.js"
1 document updated
Example
Update the address from "Valley 345" to "Canyon 123":
...
var myquery = { address: "Valley 345" };
var newvalues = { $set: { address: "Canyon 123" } };
dbo.collection("customers").updateOne(myquery, newvalues, function(err,
res) {
...
Update Many Documents
To update all documents that meets the criteria of the query, use
the updateMany() method.
Example
Update all documents where the name starts with the letter "S":
Save the code above in a file called "demo_update_many.js" and run the file:
Run "demo_update_many.js"
2 document(s) updated
Most of the information is not important to understand, but one object inside the
object is called "result" which tells us if the execution went OK, and how many
documents were affected.
You can use this object to return the number of updated documents:
Example
Return the number of updated documents:
console.log(res.result.nModified);
The limit() method takes one parameter, a number defining how many documents
to return.
customers
[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain 21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a , name: 'Betty', address: 'Green Grass 1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st 331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d , name:'Vicky', address:'Yellow Garden 2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'},
{ _id:58fdbf5c0ef8a50b4cdd9a8f , name:'William', address:'Central st 954'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: 'Main Road 989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway 1633'}
]
Example
Limit the result to only return 5 documents:
Save the code above in a file called "demo_mongodb_limit.js" and run the file:
Run "demo_mongodb_limit.js"
customers
[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain 21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'}
]
As you can see from the result above, only the 5 first documents were returned.