Node.js – Useful Resources

Node.js – Useful Resources ”; Previous Next The following resources contain additional information on Node.js. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Nodejs Course with 10 real-world Projects Most Popular 89 Lectures 17 hours Eduonix Learning Solutions More Detail Javascript & jQuery Mastery Course 79 Lectures 6.5 hours Skillbakery More Detail Finest Laravel Course – Learn from 0 to ninja with ReactJS Most Popular 166 Lectures 13 hours Paul Carlo Tordecilla More Detail Angular JS Full Stack: Create and Host Listing/Classified Site 59 Lectures 4 hours Jay R More Detail HTML5 Game Development Course : Beginner to Pro Best Seller 60 Lectures 5.5 hours Nicholas Lever More Detail Learn TypeORM for NestJS 19 Lectures 50 mins James Coonce More Detail Print Page Previous Next Advertisements ”;

Node.js – MongoDB Update

Node.js – MongoDB Update ”; Previous Next The Update operation refers to modifying the value of one or more fields in a document in a MongoDB collection. The mongodb driver for Node.js defines updateOne() and updateMany() methods. The updateOne() method is used to modify a single document, whereas the updateMany() method performs updating on more than one documents. The updateOne() method has the following syntax − collection.updateOne(query, values); The query parameter helps in finding the desired document to be updated. The values parameter contains the key:value pairs with which the document is to be modified. The updateMany() method follows the same syntax, except that the query returns multiple documents from the collection. updateOne() The following example changes price of a document with ProductID=3. The $set operator assigns a new value to the price field. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await sortdocs(client, “mydb”, “products”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function sortdocs(client, dbname, colname){ var qry = { ProductID: 3 }; var vals = { $set: { Name: “Router”, price: 2750 } }; const result = await client.db(dbname).collection(colname).updateOne(qry, vals); console.log(“Document updated”); } To verify that the document has been updated, use the Mongosh shell and enter the commands as below − > use mydb < switched to db mydb > db.products.find({“ProductID”:3}) { _id: ObjectId(“6580964f20f979d2e9a72ae9″), ProductID: 3, Name: ”Router”, price: 2750 } updateMany() Assuming that the products collection has the following documents that have the name ending with ”er”. The following sortdocs() function increments the price of all the above products by Rs. 125. We have used the $inc operator. Example async function sortdocs(client, dbname, colname){ var qry = {Name: /er$/}; var vals = { $inc: { price: 125 } }; const result = await client.db(dbname).collection(colname).updateMany(qry, vals); console.log(“Documents updated”); } Output Print Page Previous Next Advertisements ”;

Node.js – MongoDB Limit

Node.js – MongoDB Limit ”; Previous Next The Limit() method in MongoDB has a similar effect as in Limit clause in SQL. It restricts the number of documents returned by find() query to a specified number. The limit() method takes a single integer as argument. It the argument is omitted, it implies that no limit has been applied. To understand how the limit() function works, we shall use the orders collection in our database. Out of the available documents, those with price greater than or equal to 10 can be retrieved by the following code − Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await limitdocs(client, “mydb”, “orders”); } finally { await client.close(); } } main().catch(console.error); async function limitdocs(client, dbname, colname){ var myqry = {numPurchased:{$gte:10}}; const result = await client.db(dbname).collection(colname).find({“numPurchased”:{$gte:10}}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”658d7f3b30a92c8e5018a43a”,”orderId”:201,”custid”:301,”prodId”:100,”numPurchased”:20},{“_id”:”658d7f3b30a92c8e5018a43b”,”orderId”:202,”custid”:302,”prodId”:101,”numPurchased”:10},{“_id”:”658d7f3b30a92c8e5018a43d”,”orderId”:204,”custid”:303,”prodId”:103,”numPurchased”:15},{“_id”:”658d7f3b30a92c8e5018a43e”,”orderId”:205,”custid”:303,”prodId”:103,”numPurchased”:20},{“_id”:”658d7f3b30a92c8e5018a441″,”orderId”:208,”custid”:301,”prodId”:100,”numPurchased”:10},{“_id”:”658d7f3b30a92c8e5018a442″,”orderId”:209,”custid”:303,”prodId”:103,”numPurchased”:30}] Now we will apply a limit to the result returned by find() query to 1. The syntax of limit() method is as follows − collection.find(query).limit(number); Change the limitdocs() function to the following code, to obtain number of documents limited to the specified number. async function limitdocs(client, dbname, colname){ var myqry = {numPurchased:{$gte:10}}; const result = await client.db(dbname).collection(colname).find({“numPurchased”:{$gte:10}}).limit(1).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”658d7f3b30a92c8e5018a43a”,”orderId”:201,”custid”:301,”prodId”:100,”numPurchased”:20}] The find() query fetches the documents tht atisfy the filter condition, starting from its first occurrence. If you want to skip certain number of documents, use the skip() clause. collection.find(query).limit(x).skip(y) Out of the documents returned by find(), only x documents will populate the resultset, out of which first y documents will be removed. The following limitdocs() function return the second document in orders collection that has price>=10 async function limitdocs(client, dbname, colname){ var myqry = {numPurchased:{$gte:10}}; const result = await client.db(dbname).collection(colname).find({“numPurchased”:{$gte:10}}).limit(1).skip(1).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”658d7f3b30a92c8e5018a43b”,”orderId”:202,”custid”:302,”prodId”:101,”numPurchased”:10}] Print Page Previous Next Advertisements ”;

Node.js – MongoDB Query

Node.js – MongoDB Query ”; Previous Next The find() and findOne() methods defined in mongodb driver module for Node.js returns all documents or the first document from the specified collection that satisfy the query argument. You can use logical operators to construct a filter in the query object as follows − MongoDB Operators MongoDB doesn”t use traditional logical operator symbols. Instead, it has its own operators as listed below − Sr.No MongoDB Operator & Description 1 $eq equal to (==) 2 $gt greater than (>) 3 $gte greater than or equal to (>=) 4 $in if equal to any value in array 5 $lt less than (<) 6 $lte less than or equal to (<=) 7 $ne not equal to (!=) 8 $nin if not equal to any value in array The operators are used in find() method to apply filter. Following statement returns products with price>10000 Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // Create a single new listing await fetchdocs(client, “mydb”, “products”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({“price”:{$gt:10000}}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae7″,”ProductID”:1,”Name”:”Laptop”,”price”:25000},{“_id”:”6580964f20f979d2e9a72ae8″,”ProductID”:2,”Name”:”TV”,”price”:40000}] The $and as well as $or operators are available for compound logical expressions. Their usage is as follows − db.collection.find($and:[{“key1″:”value1”}, {“key2″:”value2”}]) Use following command to fetch products with price between 1000 and 10000. async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({$and:[{“price”:{$gt:1000}}, {“price”:{$lt:10000}}]}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000},{“_id”:”6580964f20f979d2e9a72aea”,”ProductID”:4,”Name”:”Scanner”,”price”:5000},{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] Regex You can also create the filter by forming regex expressions. The $regex variable is used as the key in the query JSON representation. The following code returns all the products whose name starts with P. Example async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({Name:{$regex:”^P”}}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] In the following example, the resultset contains the documents with name starting with Ro. async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({Name: /Ro/}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000}] To obtain the products with names ending with er, use the $ symbol at the end. async function fetchdocs(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({Name: /er$/}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000},{“_id”:”6580964f20f979d2e9a72aea”,”ProductID”:4,”Name”:”Scanner”,”price”:5000},{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] Print Page Previous Next Advertisements ”;

Node.js – Built-in Modules

Node.js – Built-in Modules ”; Previous Next A module in Node.js is a collection of independent and reusable code that can be imported into any Node.js application. The Node.js runtime software comes with the V8 JavaScript engine, bundled with a number of core modules, that perform important server-side tasks, such as managing event loop, perform file IO and operating system-specific functions etc. Example The following code snippet returns a list of all the built-in modules − const builtinModules = require(”repl”)._builtinLibs; console.log(builtinModules); Output [ ”assert”, ”assert/strict”, ”async_hooks”, ”buffer”, ”child_process”, ”cluster”, ”console”, ”constants”, ”crypto”, ”dgram”, ”diagnostics_channel”, ”dns”, ”dns/promises”, ”domain”, ”events”, ”fs”, ”fs/promises”, ”http”, ”http2”, ”https”, ”inspector”, ”inspector/promises”, ”module”, ”net”, ”os”, ”path”, ”path/posix”, ”path/win32”, ”perf_hooks”, ”process”, ”punycode”, ”querystring”, ”readline”, ”readline/promises”, ”repl”, ”stream”, ”stream/consumers”, ”stream/promises”, ”stream/web”, ”string_decoder”, ”sys”, ”timers”, ”timers/promises”, ”tls”, ”trace_events”, ”tty”, ”url”, ”util”, ”util/types”, ”v8”, ”vm”, ”wasi”, ”worker_threads”, ”zlib” ] Node.js has many core modules that provide essential functionalities for building applications. Here”s a list of some of the most important core modules − Sr.No Core Modules & Description 1 assert Provides a set of assertion functions for verifying invariants. 2 buffer A Buffer objects represent fixed-legth of sequence of bytes. 3 http Provides an interface for creating HTTP servers and making HTTP requests. 4 fs Provides functions for working with files and directories. 5 path Provides functions for working with file paths. 6 url Provides functions for parsing and building URLs. 7 util Provides utility functions for working with data and strings. 8 crypto Provides functions for cryptography and secure hashing. 9 process Provides information about the current Node.js process and allows you to interact with the operating system. 10 net Provides low-level networking functionality. 11 stream Provides a basic framework for working with streams of data. 12 events Provides an event emitter class for custom event handling. 13 console Provides functions for writing to the console. 14 readline Provides functions for reading line-by-line from a stream. 15 query String Provides utilities for parsing and formatting URL query strings. 16 v8 Provides functions that are specific to the version of v8. 17 os Provides functions and properties related. Print Page Previous Next Advertisements ”;

Node.js – MongoDB Delete

Node.js – MongoDB Delete ”; Previous Next The mongodb driver for Node.js includes two methods in the Collection class. The deleteOne() method deletes one document, whereas the deleteMany() method is used to delete more than on documents at a time. Both the methods need a filter argument. collection.deleteOne(filter); Note that if there are more than one documents that satisfy the given filter condition, only the first document is deleted. deleteOne() In the following example. The deleteOne() method removes a document from products collection, whose name field matches TV. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await deldocs(client, “mydb”, “products”); } finally { await client.close(); } } main().catch(console.error); async function deldocs(client, dbname, colname){ var myqry = { Name: “TV” }; const result = await client.db(dbname).collection(colname).deleteOne(myqry); console.log(“Document Deleted”); } Use MongoCompass (or MongoShell) to verify if the expected document has been removed after the above code is executed. deleteMany() The deleteMany() method also use the filter argument. However, it causes all the document satisfying the specified condition will be removed. In the code above, change the deldocs() function as follows. It results in all the documents with price>10000 to be removed. async function deldocs(client, dbname, colname){ var myqry = {“price”:{$gt:10000}}; const result = await client.db(dbname).collection(colname).deleteMany(myqry); console.log(“Documents Deleted”); } Drop Collection You can remove a collection from the database with drop() method. Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await dropcol(client, “mydb”, “products”); } finally { await client.close(); } } main().catch(console.error); async function dropcol(client, dbname, colname){ const result = await client.db(dbname).collection(colname).drop(); console.log(“Collection dropped “); } There is also a dropCollection() method available with the db object. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { await client.connect(); await dropcol(client, “mydb”, “orders”); } finally { await client.close(); } } main().catch(console.error); async function dropcol(client, dbname, colname){ const result = await client.db(dbname).dropCollection(colname); console.log(“Collection dropped”); } Print Page Previous Next Advertisements ”;

Node.js – Quick Guide

Node.js – Quick Guide ”; Previous Next Node.js – Introduction What is Node.js? Node.js is a server-side platform built on Google Chrome”s JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows − Node.js is a platform built on Chrome”s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent. Node.js = Runtime Environment + JavaScript Library Features of Node.js Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast − Being built on Google Chrome”s V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. License − Node.js is released under the MIT license. Who Uses Node.js? Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few. Projects, Applications, and Companies Using Node Concepts The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters. Where to Use Node.js? Following are the areas where Node.js is proving itself as a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications Where Not to Use Node.js? It is not advisable to use Node.js for CPU intensive applications. Node.js – Environment Setup Try it Option Online You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the available examples online and learn through practice. Feel free to modify any example and check the results with different options. Try the following example using the Live Demo option available at the top right corner of the below sample code box (on our website) − Live Demo /* Hello World! program in Node.js */ console.log(“Hello World!”); For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning. Local Environment Setup If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables. Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension “.js“. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it. The Node.js Runtime The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code. Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. Following section guides you on how to install Node.js binary distribution on various OS. Download Node.js archive Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, following are the versions available on different OS. OS Archive name Windows node-v6.3.1-x64.msi Linux node-v6.3.1-linux-x86.tar.gz Mac node-v6.3.1-darwin-x86.tar.gz SunOS node-v6.3.1-sunos-x86.tar.gz Installation on UNIX/Linux/Mac OS X, and SunOS Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv node-v6.3.1-linux-x64/* /usr/local/nodejs Add /usr/local/nodejs/bin to the PATH environment variable. OS Output Linux export PATH=$PATH:/usr/local/nodejs/bin Mac export PATH=$PATH:/usr/local/nodejs/bin FreeBSD export PATH=$PATH:/usr/local/nodejs/bin Installation on Windows Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:Program Filesnodejs. The installer should set the C:Program Filesnodejsbin directory in window”s PATH environment variable. Restart any open command prompts for the change to take effect. Verify installation: Executing a File Create a js file named main.js on your machine (Windows or Linux)

Node.js – Utility Modules

Node.js – Utility Modules ”; Previous Next There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application. Sr.No. Module Name & Description 1 OS Module Provides basic operating-system related utility functions. 2 Path Module Provides utilities for handling and transforming file paths. 3 Net Module Provides both servers and clients as streams. Acts as a network wrapper. 4 DNS Module Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities. 5 Domain Module Provides ways to handle multiple different I/O operations as a single group. Print Page Previous Next Advertisements ”;

Node.js – MongoDB Insert

Node.js – MongoDB Insert ”; Previous Next MongoDB is a document-oriented database, which can be interfaced with Node.js through the NPM module called mongodb. A Document is the heart of a MongoDB database. It is a collection of key-value pairs. We can also think of it being similar to single row in a table of SQL based relational database, just as a Collection in MongoDB is analogous to a table in relational database. The NPM mongodb package provides insertOne() and insertMany() methods, using which one or more Documents can be added into a Collection, from within a Node.js application. MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents. MongoDB documents are composed of field-and-value pairs and have the following structure − { field1: value1, field2: value2, field3: value3, … fieldN: valueN } The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. Each document is characterised by a special key called “_id” having a unique value, similar to primary key in entity table of a relational database. A key is also referred to as a field. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. insertOne() method The Collection object has insertOne() method that inserts a single document into the collection. Collection.insertOne(doc) The document to insert is passed as an argument. It inserts a single document into MongoDB. If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. Example With the following code, we insert a single document into the products collection in the database. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017”; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // Create a single new document await createdoc(client, “mydatabase”, “products”, { “ProductID”:1, “Name”:”Laptop”, “Price”:25000 }); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function createdoc(client, dbname, colname, doc){ const dbobj = await client.db(dbname); const col = dbobj.collection(colname); const result = await col.insertOne(doc); console.log(`New document created with the following id: ${result.insertedId}`); } Output New listing created with the following id: 65809214693bd4622484dce3 The Mongo shell can also be used to view the document inserted. > use mydb; < switched to db mydb > products=db[”products”] < mydb.products > docs=products.find() { _id: ObjectId(“65809214693bd4622484dce3″), ProductID: 1, Name: ”Laptop”, Price: 25000 } insertMany() method The insertMany() method of the Collection object makes it possible to insert more than one documents. An array of JSON documents is used as the argument. We also use SRV connection string the following example − Example const {MongoClient} = require(”mongodb”); async function main(){ //const uri = “mongodb://localhost:27017”; const uri = “mongodb+srv://user:[email protected]/?retryWrites=true&w=majority”; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // insert documents await createdocs(client, [ {”ProductID”:1, ”Name”:”Laptop”, ”price”:25000}, {”ProductID”:2, ”Name”:”TV”, ”price”:40000}, {”ProductID”:3, ”Name”:”Router”, ”price”:2000}, {”ProductID”:4, ”Name”:”Scanner”, ”price”:5000}, {”ProductID”:5, ”Name”:”Printer”, ”price”:9000} ]); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function createdocs(client, docs){ const result = await client.db(“mydb”).collection(“products”).insertMany(docs); console.log(`${result.insertedCount} new document(s) created with the following id(s):`); console.log(result.insertedIds); } Output 5 new listing(s) created with the following id(s): { ”0”: new ObjectId(”6580964f20f979d2e9a72ae7”), ”1”: new ObjectId(”6580964f20f979d2e9a72ae8”), ”2”: new ObjectId(”6580964f20f979d2e9a72ae9”), ”3”: new ObjectId(”6580964f20f979d2e9a72aea”), ”4”: new ObjectId(”6580964f20f979d2e9a72aeb”) } You can export the collection of document in CSV format. _id,ProductID,Name,Price,price 65809214693bd4622484dce3,1,Laptop,25000, 6580964f20f979d2e9a72ae8,2,TV,40000 6580964f20f979d2e9a72ae9,3,Router,2000 6580964f20f979d2e9a72aea,4,Scanner,5000 6580964f20f979d2e9a72aeb,5,Printer,9000 Print Page Previous Next Advertisements ”;

Node.js – MySQL Create Table

Node.js – MySQL Create Table ”; Previous Next MySQL is a RDBMS software that uses SQL to perform CRUD operations on the data stored in the tables of a relational database. In this tutorial, we are learning how to use a MySQL database as a backend to a Node.js application. This chapter describes how to create a table in a MySQL database using the Node.js program. In a relational database, a table represents an entity, characterized by one or more attributes. Each row in the table is an instance of the entity. Each entity instance is described by certain values of the table attributes. A table generally has one attribute marked as a primary key, constraining each row to have a unique value. CREATE TABLE in MySQL MySQL implements the CREATE TABLE statement as per the SQL standards. This statement defines the number and type of attributes of the table. The syntax of MySQL”s CREATE TABLE query is as follows − CREATE TABLE [IF NOT EXISTS] table_name( column1 datatype constraints, column1 datatype constraints, ) ENGINE=storage_engine; MySQL supports variety of datatypes, such as integer types (such as INT, TINYINT etc), floating-point types (FLOAT and DOUBLE), string types (VARCHAR, TEXT etc), and DATE and TIME types. To ensure data integrity of the relational database, a column may have constraints applied on it, such as PRIMARY KEY, NOT NULL, AUTO_INCREMENT etc. Let us create employee Table in the mydb database. Start the MySQL server, open the MySQL command-line client, and issue the CREATE TABLE query as below − mysql> use mydb; Database changed mysql> CREATE TABLE IF NOT EXISTS employee ( -> id INT AUTO_INCREMENT PRIMARY KEY, -> name VARCHAR(20) NOT NULL, -> age INT, -> salary FLOAT -> ); Query OK, 0 rows affected (0.09 sec) MySQL command SHOW TABLES lists all the tables in the database that is in use. mysql> SHOW TABLES; +—————-+ | Tables_in_mydb | +—————-+ | employee | +—————-+ 1 row in set (0.00 sec) CREATE TABLE in Node.js Now we have to programmatically create a MySQL table with the help of Node.js application. The process involves following steps − Include the mysql module Call createConnection() function to obtain connection object. Use the query() method of the connection object, and pass the CREATE TABLE query string to it as the first argument. To check that the table has been created, pass the SHOW TABLES query to the query() method. Example var mysql = require(”mysql”); var con = mysql.createConnection({ host: “localhost”, user: “root”, password: “mypassword”, database: “mydb” }); var qry =`CREATE TABLE IF NOT EXISTS employee ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) NOT NULL, age INT, salary FLOAT );`; con.connect(function (err) { if (err) throw err; console.log(“Connected!”); con.query(qry, function (err, result) { if (err) throw err; console.log(“Created table successfully”); }); con.query(“SHOW TABLES;”, function (err, result) { if (err) throw err; console.log(“Showing tablesn”); for (var i = 0; i < result.length; i++) { console.log(JSON.stringify(result[i])); } }) con.end(); }); Output Connected! Created table successfully Showing tables {“Tables_in_mydb”:”employee”} You can also use the DESC command that displays the fields, type, and constraints like default, primary key, etc. of each field in our table. con.query(“DESC employee;”, function (err, result) { if (err) throw err; console.log(JSON.stringify(result)); }); Output [ {“Field”:”id”,”Type”:”int”,”Null”:”NO”,”Key”:”PRI”,”Default”:null,”Extra”:”auto_increment”}, {“Field”:”name”,”Type”:”varchar(20)”,”Null”:”NO”,”Key”:””,”Default”:null,”Extra”:””}, {“Field”:”age”,”Type”:”int”,”Null”:”YES”,”Key”:””,”Default”:null,”Extra”:””}, {“Field”:”salary”,”Type”:”float”,”Null”:”YES”,”Key”:””,”Default”:null,”Extra”:””} ] Print Page Previous Next Advertisements ”;