diff --git a/data/raw/tutorial_course.json b/data/raw/tutorial_course.json new file mode 100644 index 0000000..f7ebe68 --- /dev/null +++ b/data/raw/tutorial_course.json @@ -0,0 +1,1551 @@ +{ + "title": "W3Schools Tutorial", + "source_url": "https://www.w3schools.com/nodejs/nodejs_intro.asp", + "modules": [ + { + "title": "Node.js HOME", + "url": "https://www.w3schools.com/nodejs/default.asp" + }, + { + "title": "Node.js Intro", + "url": "https://www.w3schools.com/nodejs/nodejs_intro.asp" + }, + { + "title": "Node.js Get Started", + "url": "https://www.w3schools.com/nodejs/nodejs_get_started.asp" + }, + { + "title": "Node.js Modules", + "url": "https://www.w3schools.com/nodejs/nodejs_modules.asp" + }, + { + "title": "Node.js HTTP Module", + "url": "https://www.w3schools.com/nodejs/nodejs_http.asp" + }, + { + "title": "Node.js File System", + "url": "https://www.w3schools.com/nodejs/nodejs_filesystem.asp" + }, + { + "title": "Node.js URL Module", + "url": "https://www.w3schools.com/nodejs/nodejs_url.asp" + }, + { + "title": "Node.js NPM", + "url": "https://www.w3schools.com/nodejs/nodejs_npm.asp" + }, + { + "title": "Node.js Events", + "url": "https://www.w3schools.com/nodejs/nodejs_events.asp" + }, + { + "title": "Node.js Upload Files", + "url": "https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp" + }, + { + "title": "Node.js Email", + "url": "https://www.w3schools.com/nodejs/nodejs_email.asp" + }, + { + "title": "MySQL Get Started", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql.asp" + }, + { + "title": "MySQL Create Database", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_create_db.asp" + }, + { + "title": "MySQL Create Table", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_create_table.asp" + }, + { + "title": "MySQL Insert Into", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp" + }, + { + "title": "MySQL Select From", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_select.asp" + }, + { + "title": "MySQL Where", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_where.asp" + }, + { + "title": "MySQL Order By", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_orderby.asp" + }, + { + "title": "MySQL Delete", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_delete.asp" + }, + { + "title": "MySQL Drop Table", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_drop_table.asp" + }, + { + "title": "MySQL Update", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_update.asp" + }, + { + "title": "MySQL Limit", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_limit.asp" + }, + { + "title": "MySQL Join", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_join.asp" + }, + { + "title": "MongoDB Get Started", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb.asp" + }, + { + "title": "MongoDB Create DB", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_create_db.asp" + }, + { + "title": "MongoDB Collection", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_createcollection.asp" + }, + { + "title": "MongoDB Insert", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_insert.asp" + }, + { + "title": "MongoDB Find", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp" + }, + { + "title": "MongoDB Query", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_query.asp" + }, + { + "title": "MongoDB Sort", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_sort.asp" + }, + { + "title": "MongoDB Delete", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_delete.asp" + }, + { + "title": "MongoDB Drop Collection", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_drop.asp" + }, + { + "title": "MongoDB Update", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_update.asp" + }, + { + "title": "MongoDB Limit", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_limit.asp" + }, + { + "title": "MongoDB Join", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_join.asp" + }, + { + "title": "RasPi Get Started", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi.asp" + }, + { + "title": "RasPi GPIO Introduction", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_gpio_intro.asp" + }, + { + "title": "RasPi Blinking LED", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_blinking_led.asp" + }, + { + "title": "RasPi LED & Pushbutton", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_led_pushbutton.asp" + }, + { + "title": "RasPi Flowing LEDs", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_flowing_leds.asp" + }, + { + "title": "RasPi WebSocket", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_webserver_websocket.asp" + }, + { + "title": "RasPi RGB LED WebSocket", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_rgb_led_websocket.asp" + }, + { + "title": "RasPi Components", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_components.asp" + }, + { + "title": "Built-in Modules", + "url": "https://www.w3schools.com/nodejs/ref_modules.asp" + }, + { + "title": "Node.js Compiler", + "url": "https://www.w3schools.com/nodejs/nodejs_compiler.asp" + }, + { + "title": "Node.js Server", + "url": "https://www.w3schools.com/nodejs/nodejs_server.asp" + }, + { + "title": "Node.js Syllabus", + "url": "https://www.w3schools.com/nodejs/nodejs_syllabus.asp" + }, + { + "title": "Node.js Study Plan", + "url": "https://www.w3schools.com/nodejs/nodejs_study_plan.asp" + }, + { + "title": "Node.js Certificate", + "url": "https://www.w3schools.com/nodejs/nodejs_exam.asp" + } + ], + "tutorials": [ + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/default.asp", + "content": "Node.js Tutorial\n\n❮ Home\nNext ❯\n\n\nLearn Node.js\nNode.js is an open source server environment.\nNode.js allows you to run JavaScript on the server.\nStart learning Node.js now »\n\n\nLearning by Examples\nOur \"Show Node.js\" tool makes it easy to learn Node.js, it shows both the \ncode and the result.\n\nExample\n\n var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World!');}).listen(8080); \nRun example »\n\nClick on the \"Run example\" button to see how it works.\n\nExamples Running in the Command Line Interface\nIn this tutorial there will be some examples that are better explained by displaying the result in the \ncommand line interface.\nWhen this happens, The \"Show Node.js\" tool will show the result in a black screen on the right:\n\nExample\n\nconsole.log('This example is different!');\nconsole.log('The result is displayed in the Command Line Interface'); \nRun example »\n\nClick on the \"Run example\" button to see how it works.\n\n\nTrack Your Progress\n\n\nCreate a free W3Schools account and get access to more features and learning materials:\n\nView your completed tutorials, exercises, and quizzes\nKeep an eye on your progress and daily streaks\n\nSet goals and create learning paths\nCreate your own personal website\n\nSign Up for Free\n\n\n\n\nNote: This is an optional feature. You can study at W3Schools without creating an account.\n\nNode.js Reference\nNode.js has a set of built-in modules.\nBuilt-in Modules\n\nDownload Node.js\nDownload Node.js from the official Node.js web site:\nhttps://nodejs.org\n\n\n❮ Home\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World!');}).listen(8080);" + }, + { + "language": "javascript", + "code": "console.log('This example is different!');\nconsole.log('The result is displayed in the Command Line Interface');" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_intro.asp", + "content": "Node.js Introduction\n\n❮ Previous\nNext ❯\n\n\nWhat is Node.js?\n\nNode.js is an open source server environment\nNode.js is free\nNode.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)\nNode.js uses JavaScript on the server\n\n\nWhy Node.js?\n\nNode.js uses asynchronous programming!\n\nA common task for a web server can be to open a file on the server and return the content to \nthe client.\nHere is how PHP or ASP handles a file request:\n\nSends the task to the computer's file system.\nWaits while the file system opens and reads the \n file.\nReturns the content to the client.\nReady to handle the next \nrequest.\n\nHere is how Node.js handles a file request:\n\nSends the task to the computer's file system.\nReady to handle the next request.\nWhen the file system has \nopened and read the file, the server returns the content to the client.\n\n\nNode.js eliminates the waiting, and simply continues with the next request. \n\nNode.js runs single-threaded, non-blocking, asynchronous programming, which \nis very memory efficient.\n\nWhat Can Node.js Do?\n\nNode.js can generate dynamic page content\nNode.js can create, open, read, write, delete, and close files on the server\nNode.js can collect form data\nNode.js can add, delete, modify data in your database\n\n\nWhat is a Node.js File?\n\nNode.js files contain tasks that will be executed on certain events\nA typical event is someone trying to access a port on the server\nNode.js files must be initiated on the server before having any effect\nNode.js files have extension \".js\"\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_get_started.asp", + "content": "Node.js Get Started\n\n❮ Previous\nNext ❯\n\n\nDownload Node.js\nThe official Node.js website has installation instructions for Node.js:\nhttps://nodejs.org\n\nGetting Started\nOnce you have downloaded and installed Node.js on your computer, let's try to \ndisplay \"Hello World\" in a web browser.\nCreate a Node.js file named \"myfirst.js\", and add the following \ncode:\n\nmyfirst.js\n\n var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});\n \n res.end('Hello World!');}).listen(8080);\n\nSave the file on your computer: C:\\Users\\Your Name\\myfirst.js\nThe code \ntells the computer to write \"Hello World!\" if anyone (e.g. a web browser) tries \nto access your computer on port 8080.\nFor now, you do not have to \nunderstand the code. It will be explained later.\n\nCommand Line Interface\nNode.js files must be initiated in the \"Command Line Interface\" program \nof your computer.\nHow to open the command line interface on your computer depends on the operating system. For Windows users, press the start button and look for \n\"Command \nPrompt\", or simply write \"cmd\" in the search field.\nNavigate to the folder that contains the file \"myfirst.js\", the \ncommand line interface \nwindow should look something like this:\n\n\nC:\\Users\\Your Name>_\n\n\n\nInitiate the Node.js File\nThe file you have just created must be initiated by Node.js before any action \ncan take place.\nStart your command line interface, write node myfirst.js and hit enter:\n\nInitiate \"myfirst.js\":\n\n C:\\Users\\Your Name>node myfirst.js\n\n\nNow, your computer works as a server!\nIf anyone tries to access your computer on port 8080, they will get a \"Hello \nWorld!\" message in return!\nStart your internet browser, and type in the address: http://localhost:8080\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});\n \n res.end('Hello World!');}).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>_" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node myfirst.js" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_modules.asp", + "content": "Node.js Modules\n\n❮ Previous\nNext ❯\n\n\nWhat is a Module in Node.js?\nConsider modules to be the same as JavaScript libraries.\nA set of functions you want to include in your application.\n\nBuilt-in Modules\nNode.js has a set of built-in modules which you can use without any further \ninstallation.\nLook at our Built-in Modules Reference for a \ncomplete list of modules.\n\nInclude Modules\nTo include a module, use the require() \nfunction with the name of the module:\n\n\n var http = require('http');\n\nNow your application has access to the HTTP module, and is able to create a server:\n\n\n http.createServer(function (req, res) { \n res.writeHead(200, {'Content-Type': 'text/html'}); \n res.end('Hello World!');}).listen(8080);\n\n\nCreate Your Own Modules\nYou can create your own modules, and easily include them in your applications.\nThe following example creates a module that returns a date and time object:\n\nExample\nCreate a module that returns the current date and time:\n\n exports.myDateTime = function () { return Date();};\n\nUse the exports keyword to make properties and methods available outside the module file.\nSave the code above in a file called \"myfirstmodule.js\"\n\n\n\n\n\n\nInclude Your Own Module\nNow you can include and use the module in any of your Node.js files.\n\nExample\nUse the module \"myfirstmodule\" in a Node.js file:\n\n var http = require('http');\nvar dt = require('./myfirstmodule');\n http.createServer(function (req, res) { \n res.writeHead(200, {'Content-Type': 'text/html'}); \n res.write(\"The date and time are currently: \" + dt.myDateTime());\n \n res.end();\n }).listen(8080);\nRun example »\n\nNotice that we use ./ to locate the module, that means that the \nmodule is located in the same folder as the Node.js file.\nSave the code above in a file called \"demo_module.js\", and initiate the file:\n\nInitiate demo_module.js:\n\nC:\\Users\\Your Name>node demo_module.js\n\n\nIf you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var http = require('http');" + }, + { + "language": "javascript", + "code": "http.createServer(function (req, res) { \n res.writeHead(200, {'Content-Type': 'text/html'}); \n res.end('Hello World!');}).listen(8080);" + }, + { + "language": "javascript", + "code": "exports.myDateTime = function () { return Date();};" + }, + { + "language": "javascript", + "code": "var http = require('http');\nvar dt = require('./myfirstmodule');\n http.createServer(function (req, res) { \n res.writeHead(200, {'Content-Type': 'text/html'}); \n res.write(\"The date and time are currently: \" + dt.myDateTime());\n \n res.end();\n }).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_module.js" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_http.asp", + "content": "Node.js HTTP Module\n\n❮ Previous\nNext ❯\n\n\nThe Built-in HTTP Module\nNode.js has a built-in module called HTTP, which allows Node.js to transfer \ndata over the Hyper Text Transfer Protocol (HTTP).\nTo include the HTTP module, use the\nrequire() method:\n\n\n var http = require('http');\n\n\nNode.js as a Web Server\nThe HTTP module can create an HTTP server that listens to \nserver ports and gives a response back to \nthe client.\nUse the createServer() method to create an \nHTTP server:\n\nExample\n\n var http = require('http');//create a server object:http.createServer(function \n (req, res) { res.write('Hello World!'); //write a response to the \n client res.end(); //end the response}).listen(8080); //the \n server object listens on port 8080\nRun example »\n\nThe function passed into the http.createServer() \nmethod, will be executed when someone tries to access the \ncomputer on port 8080.\nSave the code above in a file called \"demo_http.js\", and initiate \nthe file:\n\nInitiate demo_http.js:\n\nC:\\Users\\Your Name>node demo_http.js\n\n\nIf you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080\n\n\n\n\n\n\nAdd an HTTP Header\nIf the response from the HTTP server is supposed to be displayed as HTML, you \nshould include an HTTP header with the correct content type:\n\nExample\n\n var http = require('http');http.createServer(function \n (req, res) { res.writeHead(200, \n {'Content-Type': 'text/html'}); res.write('Hello \n World!'); res.end();}).listen(8080);\nRun example »\n\nThe first argument of the res.writeHead() method is the status code, 200 means \nthat \nall is OK, the second argument is an object containing the response headers.\n\nRead the Query String\nThe function passed into the http.createServer() \nhas a req argument that represents the request from the \nclient, as an object (http.IncomingMessage object).\nThis object has a property called \"url\" which holds the \npart of the url that comes after the domain name:\n\ndemo_http_url.js\n\n var http = require('http');http.createServer(function \n (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});\n res.write(req.url); \n res.end();}).listen(8080);\n\nSave the code above in a file called \"demo_http_url.js\" and \ninitiate the file:\n\nInitiate demo_http_url.js:\n\nC:\\Users\\Your Name>node demo_http_url.js\n\n\nIf you have followed the same steps on your computer, you should see two \ndifferent results when opening these two addresses:\nhttp://localhost:8080/summer\n\nWill produce this result:\n\n/summer\nRun example »\n\nhttp://localhost:8080/winter\n\nWill produce this result:\n\n/winter\nRun example »\n\n\nSplit the Query String\nThere are built-in modules to easily split the query string into readable \nparts, such as the URL module.\n\nExample\nSplit the query string into readable parts:\n\n var http = require('http');var url = require('url');\n\n http.createServer(function (req, res) { res.writeHead(200, \n {'Content-Type': 'text/html'}); var q = url.parse(req.url, \n true).query; var txt = q.year + \" \" + \n q.month; res.end(txt);\n }).listen(8080);\n\n\nSave the code above in a file called \"demo_querystring.js\" and \ninitiate the file:\n\nInitiate demo_querystring.js:\n\nC:\\Users\\Your Name>node demo_querystring.js\n\n\nThe address:\n\nhttp://localhost:8080/?year=2017&month=July\n\n\nWill produce this result:\n\n2017 July\nRun example »\n\nRead more about the URL module in the Node.js URL \nModule chapter.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var http = require('http');" + }, + { + "language": "javascript", + "code": "var http = require('http');//create a server object:http.createServer(function \n (req, res) { res.write('Hello World!'); //write a response to the \n client res.end(); //end the response}).listen(8080); //the \n server object listens on port 8080" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_http.js" + }, + { + "language": "javascript", + "code": "var http = require('http');http.createServer(function \n (req, res) { res.writeHead(200, \n {'Content-Type': 'text/html'}); res.write('Hello \n World!'); res.end();}).listen(8080);" + }, + { + "language": "javascript", + "code": "var http = require('http');http.createServer(function \n (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});\n res.write(req.url); \n res.end();}).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_http_url.js" + }, + { + "language": "javascript", + "code": "/summer" + }, + { + "language": "javascript", + "code": "/winter" + }, + { + "language": "javascript", + "code": "var http = require('http');var url = require('url');\n\n http.createServer(function (req, res) { res.writeHead(200, \n {'Content-Type': 'text/html'}); var q = url.parse(req.url, \n true).query; var txt = q.year + \" \" + \n q.month; res.end(txt);\n }).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_querystring.js" + }, + { + "language": "javascript", + "code": "2017 July" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_filesystem.asp", + "content": "Node.js File System Module\n\n❮ Previous\nNext ❯\n\n\nNode.js as a File Server\nThe Node.js file system module allows you to work with the file system on your \ncomputer.\nTo include the File System module, use the \nrequire() method:\n\n\n var fs = require('fs');\n\nCommon use for the File System module:\n\nRead files\nCreate files\nUpdate files\nDelete files\nRename files\n\n\nRead Files\nThe fs.readFile() method is used to read files on your computer.\nAssume we have the following HTML file (located in the same folder as \nNode.js):\n\ndemofile1.html\n\n
My paragraph.
\n \n\nCreate a Node.js file that reads the HTML file, \nand return the content:\n\nExample\n\n var http = require('http');var fs = require('fs');http.createServer(function \n (req, res) { fs.readFile('demofile1.html', function(err, data) {\n \n res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); \n return res.end(); });}).listen(8080);\nRun example »\n\nSave the code above in a file called \"demo_readfile.js\", and initiate the \nfile:\n\nInitiate demo_readfile.js:\n\nC:\\Users\\Your Name>node demo_readfile.js\n\n\nIf you have followed the same steps on your computer, you will see the same \nresult as the example: http://localhost:8080\n\n\n\n\n\n\nCreate Files\nThe File System module has methods for creating new files:\n\nfs.appendFile()\nfs.open()\nfs.writeFile()\n\nThe fs.appendFile() method appends specified content to a file. If the \nfile does not exist, the file will be created:\n\nExample\nCreate a new file using the appendFile() method:\n\n var fs = require('fs');fs.appendFile('mynewfile1.txt', 'Hello \n content!', function (err) { if (err) throw err; console.log('Saved!');\n });\nRun example »\n\nThe fs.open() method takes a \"flag\" as the second argument, if the \nflag is \"w\" for \"writing\", the specified file is opened for writing. If the file \ndoes not exist, an empty file is created:\n\nExample\nCreate a new, empty file using the open() method:\n\n var fs = require('fs');fs.open('mynewfile2.txt', 'w', function (err, \n file) { if (err) throw err; console.log('Saved!');});\nRun example »\n\nThe fs.writeFile() method replaces the specified file and content if it exists. \nIf the file does not exist, a new file, containing the specified content, will \nbe created:\n\nExample\nCreate a new file using the writeFile() method:\n\n var fs = require('fs');fs.writeFile('mynewfile3.txt', 'Hello \n content!', function (err) { if (err) throw err; \n console.log('Saved!');});\nRun example »\n\n\nUpdate Files\nThe File System module has methods for updating files:\n\nfs.appendFile()\nfs.writeFile()\n\nThe fs.appendFile() method appends the specified content at the end of the specified file:\n\nExample\nAppend \"This is my text.\" to the end of the file \"mynewfile1.txt\":\n\n var fs = require('fs');fs.appendFile('mynewfile1.txt', ' This is my \n text.', function (err) { if (err) throw err; console.log('Updated!');\n });\nRun example »\n\nThe fs.writeFile() method replaces the specified file and content:\n\nExample\nReplace the content of the file \"mynewfile3.txt\":\n\n var fs = require('fs');fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if (err) throw err; \n console.log('Replaced!');});\nRun example »\n\n\nDelete Files\nTo delete a file with the File System module, use the fs.unlink() \nmethod.\nThe fs.unlink() method deletes the specified file:\n\nExample\nDelete \"mynewfile2.txt\":\n\n var fs = require('fs');fs.unlink('mynewfile2.txt', function (err) { \n if (err) throw err; console.log('File deleted!');});\nRun example »\n\n\nRename Files\nTo rename a file with the File System module, use the fs.rename() \nmethod.\nThe fs.rename() method renames the specified file:\n\nExample\nRename \"mynewfile1.txt\" to \"myrenamedfile.txt\":\n\n var fs = require('fs');fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) { \n if (err) throw err; console.log('File Renamed!');});\nRun example »\n\n\nUpload Files\nYou can also use Node.js to upload files to your computer.\nRead how in our Node.js Upload Files chapter.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var fs = require('fs');" + }, + { + "language": "javascript", + "code": "My paragraph.
\n " + }, + { + "language": "javascript", + "code": "var http = require('http');var fs = require('fs');http.createServer(function \n (req, res) { fs.readFile('demofile1.html', function(err, data) {\n \n res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); \n return res.end(); });}).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_readfile.js" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.appendFile('mynewfile1.txt', 'Hello \n content!', function (err) { if (err) throw err; console.log('Saved!');\n });" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.open('mynewfile2.txt', 'w', function (err, \n file) { if (err) throw err; console.log('Saved!');});" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.writeFile('mynewfile3.txt', 'Hello \n content!', function (err) { if (err) throw err; \n console.log('Saved!');});" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.appendFile('mynewfile1.txt', ' This is my \n text.', function (err) { if (err) throw err; console.log('Updated!');\n });" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if (err) throw err; \n console.log('Replaced!');});" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.unlink('mynewfile2.txt', function (err) { \n if (err) throw err; console.log('File deleted!');});" + }, + { + "language": "javascript", + "code": "var fs = require('fs');fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) { \n if (err) throw err; console.log('File Renamed!');});" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_url.asp", + "content": "Node.js URL Module\n\n❮ Previous\nNext ❯\n\n\nThe Built-in URL Module\nThe URL module splits up a web address into readable parts.\nTo include the URL module, use the require() \nmethod:\n\n\n var url = require('url');\n\nParse an address with the url.parse() \nmethod, and it will return a URL object with each part of the address as \nproperties:\n\nExample\nSplit a web address into readable parts:\n\n var url = require('url');\n var adr = 'http://localhost:8080/default.htm?year=2017&month=february';\n var q = url.parse(adr, true);\n console.log(q.host); //returns 'localhost:8080'\n console.log(q.pathname); //returns '/default.htm'console.log(q.search); //returns '?year=2017&month=february'\n var qdata = q.query; //returns an object: { year: 2017, month: 'february' }\n console.log(qdata.month); //returns 'february'\n\nRun example »\n\n\nNode.js File Server\nNow we know how to parse the query string, and in the previous chapter we \nlearned how to make Node.js behave as a file \nserver. Let us combine the two, and serve the file requested by the client.\nCreate two html files and save them in the same folder as your node.js files.\n\nsummer.html\n\nI love \n the sun!
\n \n\n\nwinter.html\n\nI love \n the snow!
\n \n\n\n\n\n\n\n\nCreate a Node.js file that opens the requested file and returns the content \nto the client. If anything goes wrong, throw a 404 error:\n\ndemo_fileserver.js:\n\n var http = require('http');var url = require('url');var fs = require('fs');\nhttp.createServer(function \n (req, res) { var q = url.parse(req.url, true); var \n filename = \".\" + q.pathname; fs.readFile(filename, \n function(err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); \n return res.end(\"404 Not Found\"); } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); \n return res.end(); });}).listen(8080);\n\nRemember to initiate the file:\n\nInitiate demo_fileserver.js:\n\nC:\\Users\\Your Name>node demo_fileserver.js\n\n\nIf you have followed the same steps on your computer, you should see two \ndifferent results when opening these two addresses:\nhttp://localhost:8080/summer.html\n\nWill produce this result:\n\nSummer\nI love the sun!\n\n\nhttp://localhost:8080/winter.html\n\nWill produce this result:\n\nWinter\nI love the snow!\n\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var url = require('url');" + }, + { + "language": "javascript", + "code": "var url = require('url');\n var adr = 'http://localhost:8080/default.htm?year=2017&month=february';\n var q = url.parse(adr, true);\n console.log(q.host); //returns 'localhost:8080'\n console.log(q.pathname); //returns '/default.htm'console.log(q.search); //returns '?year=2017&month=february'\n var qdata = q.query; //returns an object: { year: 2017, month: 'february' }\n console.log(qdata.month); //returns 'february'" + }, + { + "language": "javascript", + "code": "I love \n the sun!
\n " + }, + { + "language": "javascript", + "code": "I love \n the snow!
\n " + }, + { + "language": "javascript", + "code": "var http = require('http');var url = require('url');var fs = require('fs');\nhttp.createServer(function \n (req, res) { var q = url.parse(req.url, true); var \n filename = \".\" + q.pathname; fs.readFile(filename, \n function(err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); \n return res.end(\"404 Not Found\"); } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); \n return res.end(); });}).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_fileserver.js" + }, + { + "language": "javascript", + "code": "Summer\nI love the sun!" + }, + { + "language": "javascript", + "code": "Winter\nI love the snow!" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_npm.asp", + "content": "Node.js NPM\n\n❮ Previous\nNext ❯\n\n\nWhat is NPM?\nNPM is a package manager for Node.js packages, or modules if you like.\nwww.npmjs.com hosts thousands of \nfree packages to download and use.\nThe NPM program is installed on your computer when you install Node.js\n\nNPM is already ready to run on your computer!\n\n\nWhat is a Package?\nA package in Node.js contains all the files you need for a module.\nModules are JavaScript libraries you can include in your project.\n\nDownload a Package\nDownloading a package is very easy.\nOpen the command line interface and tell NPM to download the package you want.\nI want to download a package called \"upper-case\":\n\nDownload \"upper-case\":\n\nC:\\Users\\Your Name>npm install upper-case\n\n\nNow you have downloaded and installed your first package!\nNPM creates a folder named \"node_modules\", where the package will be placed. \nAll packages you install in the future will be \nplaced in this folder.\nMy project now has a folder structure like this:\nC:\\Users\\My Name\\node_modules\\upper-case\n\n\n\n\n\n\nUsing a Package\nOnce the package is installed, it is ready to use.\nInclude the \"upper-case\" package the same way you include any other \nmodule:\n\n\n var uc = require('upper-case');\n\nCreate a Node.js file that will convert the output \"Hello World!\" into upper-case letters:\n\nExample\n\n var http = require('http');var uc = require('upper-case');http.createServer(function \n (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});\n res.write(uc.upperCase(\"Hello \n World!\")); \n res.end();}).listen(8080);\nRun example »\n\nSave the code above in a file called \"demo_uppercase.js\", and initiate the file:\n\nInitiate demo_uppercase:\n\nC:\\Users\\Your Name>node demo_uppercase.js\n\n\nIf you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "C:\\Users\\Your Name>npm install upper-case" + }, + { + "language": "javascript", + "code": "var uc = require('upper-case');" + }, + { + "language": "javascript", + "code": "var http = require('http');var uc = require('upper-case');http.createServer(function \n (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});\n res.write(uc.upperCase(\"Hello \n World!\")); \n res.end();}).listen(8080);" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_uppercase.js" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_events.asp", + "content": "Node.js Events\n\n❮ Previous\nNext ❯\n\n\nNode.js is perfect for event-driven applications.\n\nEvents in Node.js\nEvery action on a computer is an event. Like when a connection is made or a \nfile is opened.\nObjects in Node.js can fire events, like the readStream object fires \nevents when opening and closing a file:\n\nExample\n\n var fs = require('fs');var rs = fs.createReadStream('./demofile.txt');\n rs.on('open', function () { console.log('The file is open');\n });\nRun example »\n\n\nEvents Module\nNode.js has a \nbuilt-in module, called \"Events\", where you can create-, fire-, and listen for- your own \nevents.\nTo include the built-in Events module use the require() \nmethod. In addition, all event properties and methods are an instance of an \nEventEmitter object. To be able to access these properties and methods, create \nan EventEmitter object:\n\n\n var events = require('events');var eventEmitter = new events.EventEmitter();\n\n\nThe EventEmitter Object\nYou can assign event handlers to your own events with the EventEmitter \nobject.\nIn the example below we have created a function that will be \nexecuted when a \"scream\" event is fired.\nTo fire an event, use the emit() method.\n\nExample\n\n var events = require('events');var eventEmitter = new events.EventEmitter();\n//Create an event handler:var myEventHandler = function () { \n console.log('I hear a scream!');}//Assign the event handler to an \n event:eventEmitter.on('scream', myEventHandler);//Fire the \n 'scream' event:eventEmitter.emit('scream');\nRun example »\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var fs = require('fs');var rs = fs.createReadStream('./demofile.txt');\n rs.on('open', function () { console.log('The file is open');\n });" + }, + { + "language": "javascript", + "code": "var events = require('events');var eventEmitter = new events.EventEmitter();" + }, + { + "language": "javascript", + "code": "var events = require('events');var eventEmitter = new events.EventEmitter();\n//Create an event handler:var myEventHandler = function () { \n console.log('I hear a scream!');}//Assign the event handler to an \n event:eventEmitter.on('scream', myEventHandler);//Fire the \n 'scream' event:eventEmitter.emit('scream');" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp", + "content": "Node.js Upload Files\n\n❮ Previous\nNext ❯\n\n\nThe Formidable Module\nThere is a very good module for working with file uploads, called \"Formidable\".\nThe Formidable module can be downloaded and installed using NPM:\n\n\nC:\\Users\\Your Name>npm install formidable\n\nAfter you have downloaded the Formidable module, you can include the module \nin any application:\n\n\n var formidable = require('formidable');\n\n\nUpload Files\nNow you are ready to make a web page in Node.js that lets the user upload \nfiles to your computer:\nStep 1: Create an Upload Form\nCreate a Node.js file that writes an HTML form, with an upload field:\n\nExample\nThis code will produce an HTML form:\n\n var http = require('http');http.createServer(function \n (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(''); \n return res.end();}).listen(8080);\n\nStep 2: Parse the Uploaded File\nInclude the Formidable module to be able to parse the uploaded file once it \nreaches the server.\nWhen the file is uploaded and parsed, it gets placed on a temporary folder on your computer.\n\nExample\nThe file will be uploaded, and placed on a temporary folder:\n\n var http = require('http');var formidable = require('formidable');\nhttp.createServer(function \n (req, res) { if (req.url == '/fileupload') { \n var form = new formidable.IncomingForm(); form.parse(req, \n function (err, fields, files) { res.write('File \n uploaded'); res.end(); });\n \n } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(''); \n return res.end(); }}).listen(8080);\n\n\n\n\n\n\n\nStep 3: Save the File\nWhen a file is successfully uploaded to the server, it is placed on a \ntemporary folder.\nThe path to this directory can be found in the \"files\" object, passed as the \nthird argument in the parse() method's callback function.\nTo move the file to the folder of your choice, use the File System module, \nand rename the file:\n\nExample\nInclude the fs module, and move the file to the current folder:\n\n var http = require('http');var formidable = require('formidable');\nvar fs = require('fs');http.createServer(function \n (req, res) { if (req.url == '/fileupload') { \n var form = new formidable.IncomingForm(); form.parse(req, \n function (err, fields, files) { var \n oldpath = files.filetoupload.filepath; var \n newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename; \n fs.rename(oldpath, newpath, function (err) { if (err) throw \n err; res.write('File uploaded \n and moved!'); res.end(); \n }); }); \n } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(''); \n return res.end(); }}).listen(8080);\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "C:\\Users\\Your Name>npm install formidable" + }, + { + "language": "javascript", + "code": "var formidable = require('formidable');" + }, + { + "language": "javascript", + "code": "var http = require('http');http.createServer(function \n (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(''); \n return res.end();}).listen(8080);" + }, + { + "language": "javascript", + "code": "var http = require('http');var formidable = require('formidable');\nhttp.createServer(function \n (req, res) { if (req.url == '/fileupload') { \n var form = new formidable.IncomingForm(); form.parse(req, \n function (err, fields, files) { res.write('File \n uploaded'); res.end(); });\n \n } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(''); \n return res.end(); }}).listen(8080);" + }, + { + "language": "javascript", + "code": "var http = require('http');var formidable = require('formidable');\nvar fs = require('fs');http.createServer(function \n (req, res) { if (req.url == '/fileupload') { \n var form = new formidable.IncomingForm(); form.parse(req, \n function (err, fields, files) { var \n oldpath = files.filetoupload.filepath; var \n newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename; \n fs.rename(oldpath, newpath, function (err) { if (err) throw \n err; res.write('File uploaded \n and moved!'); res.end(); \n }); }); \n } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(''); \n return res.end(); }}).listen(8080);" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_email.asp", + "content": "Node.js Send an Email\n\n❮ Previous\nNext ❯\n\n\nThe Nodemailer Module\nThe Nodemailer module makes it easy to send emails from your computer.\nThe Nodemailer module can be downloaded and installed using npm:\n\n\nC:\\Users\\Your Name>npm install nodemailer\n\nAfter you have downloaded the Nodemailer module, you can include the module \nin any application:\n\n\n var nodemailer = require('nodemailer');\n\n\nSend an Email\nNow you are ready to send emails from your server.\nUse the username and password from your selected email provider to send an \nemail. This tutorial will show you how to use your Gmail account to send an \nemail:\n\nExample\n\n var nodemailer = require('nodemailer');var transporter = \n nodemailer.createTransport({ service: 'gmail', auth: { \n user: 'youremail@gmail.com', \n pass: 'yourpassword' }});var mailOptions = { \n from: 'youremail@gmail.com', \n to: 'myfriend@yahoo.com', subject: 'Sending Email using Node.js', text: \n 'That was easy!'};transporter.sendMail(mailOptions, \n function(error, info){ if (error) { console.log(error); } else {\n \n console.log('Email sent: ' + info.response); }});\n\nAnd that's it! Now your server is able to send emails.\n\n\n\n\n\n\nMultiple Receivers\nTo send an email to more than one receiver, add them to the \"to\" property of the mailOptions object, separated by commas:\n\nExample\nSend email to more than one address:\n\n var mailOptions = { \n from: 'youremail@gmail.com', \n to: 'myfriend@yahoo.com, \nmyotherfriend@yahoo.com',\n subject: 'Sending Email using Node.js', text: \n'That was easy!'}\n\n\nSend HTML\nTo send HTML formatted text in your email, use the \"html\" property instead of \nthe \"text\" property:\n\nExample\nSend email containing HTML:\n\n var mailOptions = { \n from: 'youremail@gmail.com', \n to: 'myfriend@yahoo.com',\n subject: 'Sending Email using Node.js', html: \n'That was easy!
'}\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "C:\\Users\\Your Name>npm install nodemailer" + }, + { + "language": "javascript", + "code": "var nodemailer = require('nodemailer');" + }, + { + "language": "javascript", + "code": "var nodemailer = require('nodemailer');var transporter = \n nodemailer.createTransport({ service: 'gmail', auth: { \n user: 'youremail@gmail.com', \n pass: 'yourpassword' }});var mailOptions = { \n from: 'youremail@gmail.com', \n to: 'myfriend@yahoo.com', subject: 'Sending Email using Node.js', text: \n 'That was easy!'};transporter.sendMail(mailOptions, \n function(error, info){ if (error) { console.log(error); } else {\n \n console.log('Email sent: ' + info.response); }});" + }, + { + "language": "javascript", + "code": "var mailOptions = { \n from: 'youremail@gmail.com', \n to: 'myfriend@yahoo.com, \nmyotherfriend@yahoo.com',\n subject: 'Sending Email using Node.js', text: \n'That was easy!'}" + }, + { + "language": "javascript", + "code": "var mailOptions = { \n from: 'youremail@gmail.com', \n to: 'myfriend@yahoo.com',\n subject: 'Sending Email using Node.js', html: \n'That was easy!
'}" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql.asp", + "content": "Node.js MySQL\n\n❮ Previous\nNext ❯\n\n\nNode.js can be used in database applications.\nOne of the most popular databases is MySQL.\n\nMySQL Database\nTo be able to experiment with the code examples, you should have MySQL installed \non your computer.\nYou can download a free MySQL database at https://www.mysql.com/downloads/.\n\nInstall MySQL Driver\nOnce you have MySQL up and running on your computer, you can access it by \nusing Node.js.\nTo access a MySQL database with Node.js, you need a MySQL driver. This \ntutorial will use the \"mysql\" module, downloaded from NPM.\nTo download and install the \"mysql\" module, open the Command Terminal and execute the following:\n\n\nC:\\Users\\Your Name>npm install mysql\n\n\nNow you have downloaded and installed a mysql database driver.\nNode.js can use this module to manipulate the MySQL database:\n\n\n var mysql = require('mysql');\n\n\n\n\n\n\n\nCreate Connection\nStart by creating a connection to the database.\nUse the username and password from your MySQL database.\n\ndemo_db_connection.js\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");});\nRun example »\n\nSave the code above in a file called \"demo_db_connection.js\" and run the file:\n\nRun \"demo_db_connection.js\"\n\nC:\\Users\\Your Name>node demo_db_connection.js\n\n\nWhich will give you this result:\n\n\nConnected!\n\nNow you can start querying the database using SQL statements.\n\nQuery a Database\nUse SQL statements to read from (or write to) a MySQL database. This \nis also called \"to query\" the database.\nThe connection object created in the example above, has a method for querying the database:\n\n\n con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");\n \n con.query(sql, function (err, result) { if (err) throw err; console.log(\"Result: \n \" + result); });});\n\nThe query method takes an sql statements as a parameter and returns the \nresult.\nLearn how to read, write, delete, and update a database in the next chapters.\nRead more about SQL statements in our SQL Tutorial.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "C:\\Users\\Your Name>npm install mysql" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_connection.js" + }, + { + "language": "javascript", + "code": "Connected!" + }, + { + "language": "javascript", + "code": "con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");\n \n con.query(sql, function (err, result) { if (err) throw err; console.log(\"Result: \n \" + result); });});" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_create_db.asp", + "content": "Node.js MySQL Create Database\n\n❮ Previous\nNext ❯\n\n\nCreating a Database\nTo create a database in MySQL, use the \"CREATE DATABASE\" statement:\n\nExample\nCreate a database named \"mydb\":\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n con.query(\"CREATE DATABASE mydb\", function (err, result) {\n if (err) throw err; console.log(\"Database \n created\"); });});\nRun example »\n\nSave the code above in a file called \"demo_create_db.js\" and run the file:\n\nRun \"demo_create_db.js\"\n\nC:\\Users\\Your Name>node demo_create_db.js\n\n\nWhich will give you this result:\n\n\nConnected!Database created\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n con.query(\"CREATE DATABASE mydb\", function (err, result) {\n if (err) throw err; console.log(\"Database \n created\"); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_create_db.js" + }, + { + "language": "javascript", + "code": "Connected!Database created" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_create_table.asp", + "content": "Node.js MySQL Create Table\n\n❮ Previous\nNext ❯\n\n\nCreating a Table\nTo create a table in MySQL, use the \"CREATE TABLE\" statement.\nMake sure you define the name of the database when you create the connection:\n\nExample\nCreate a table named \"customers\":\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n var sql = \"CREATE TABLE customers (name VARCHAR(255), \n address VARCHAR(255))\"; \n con.query(sql, function (err, result) { if (err) \n throw err; console.log(\"Table created\"); });});\nRun example »\n\nSave the code above in a file called \"demo_create_table.js\" and run the file:\n\nRun \"demo_create_table.js\"\n\nC:\\Users\\Your Name>node demo_create_table.js\n\n\nWhich will give you this result:\n\n\nConnected!Table created\n\n\n\n\n\n\n\nPrimary Key\nWhen creating a table, you should also create a column with a unique key for each \nrecord.\nThis can be done by defining a column as \"INT AUTO_INCREMENT PRIMARY KEY\" which will insert a \nunique number for each record. Starting at 1, and increased by one for each \nrecord.\n\nExample\nCreate primary key when creating the table:\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n var sql = \"CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY \n KEY, name VARCHAR(255), \n address VARCHAR(255))\"; \n con.query(sql, function (err, result) { if (err) \n throw err; console.log(\"Table created\"); });});\nRun example »\n\nIf the table already exists, use the ALTER TABLE keyword:\n\nExample\nCreate primary key on an existing table:\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n var sql = \"ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT \n PRIMARY KEY\"; \n con.query(sql, function (err, result) { if (err) \n throw err; console.log(\"Table altered\"); });});\nRun example »\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n var sql = \"CREATE TABLE customers (name VARCHAR(255), \n address VARCHAR(255))\"; \n con.query(sql, function (err, result) { if (err) \n throw err; console.log(\"Table created\"); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_create_table.js" + }, + { + "language": "javascript", + "code": "Connected!Table created" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n var sql = \"CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY \n KEY, name VARCHAR(255), \n address VARCHAR(255))\"; \n con.query(sql, function (err, result) { if (err) \n throw err; console.log(\"Table created\"); });});" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\"); \n var sql = \"ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT \n PRIMARY KEY\"; \n con.query(sql, function (err, result) { if (err) \n throw err; console.log(\"Table altered\"); });});" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp", + "content": "Node.js MySQL Insert Into\n\n❮ Previous\nNext ❯\n\n\nInsert Into Table\nTo fill a table in MySQL, use the \"INSERT INTO\" statement.\n\nExample\nInsert a record in the \"customers\" table:\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");\n var sql = \"INSERT INTO customers (name, address) \n VALUES ('Company Inc', 'Highway 37')\"; \n con.query(sql, function (err, result) { if (err) throw err; console.log(\"1 record inserted\"); });});\nRun example »\n\nSave the code above in a file called \"demo_db_insert.js\", and run the file:\n\nRun \"demo_db_insert.js\"\n\nC:\\Users\\Your Name>node demo_db_insert.js\n\n\nWhich will give you this result:\n\n\nConnected!1 record inserted\n\n\n\n\n\n\n\nInsert Multiple Records\nTo insert more than one record, make an array containing the values, and \ninsert a question mark in the sql, which will be replaced by the value array:\nINSERT INTO customers (name, address) VALUES ?\n\nExample\nFill the \"customers\" table with data:\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\n con.connect(function(err) { if (err) throw err; \n console.log(\"Connected!\"); var sql = \"INSERT INTO customers (name, \n address) VALUES ?\"; var values = [ ['John', \n 'Highway 71'], ['Peter', 'Lowstreet 4'], \n ['Amy', 'Apple st 652'], ['Hannah', 'Mountain 21'], \n ['Michael', 'Valley 345'], ['Sandy', 'Ocean blvd 2'], \n ['Betty', 'Green Grass 1'], ['Richard', 'Sky st 331'], \n ['Susan', 'One way 98'], ['Vicky', 'Yellow Garden 2'], \n ['Ben', 'Park Lane 38'], ['William', 'Central st 954'], \n ['Chuck', 'Main Road 989'], ['Viola', 'Sideway 1633'] \n ]; con.query(sql, [values], function (err, result) \n { if (err) throw err; console.log(\"Number \n of records inserted: \" + result.affectedRows); });});\nRun example »\n\nSave the code above in a file called \"demo_db_insert_multple.js\", and run the file:\n\nRun \"demo_db_insert_multiple.js\"\n\nC:\\Users\\Your Name>node demo_db_insert_multiple.js\n\n\nWhich will give you this result:\n\n\nConnected!Number of records inserted: 14\n\n\nThe Result Object\nWhen executing a query, a result object is returned.\nThe result object contains information about how the query \naffected the table.\nThe result object returned from the example above looks like this:\n\n\n { fieldCount: 0, affectedRows: 14, insertId: 0, \n serverStatus: 2, warningCount: 0, message: '\\'Records:14 \n Duplicated: 0 Warnings: 0', protocol41: true, \n changedRows: 0}\n\nThe values of the properties can be displayed like this:\n\nExample\nReturn the number of affected rows:\n\nconsole.log(result.affectedRows)\n\n\nWhich will produce this result:\n\n\n14\n\n\nGet Inserted ID\nFor tables with an auto increment id field, you can get the id of the row you \njust inserted by asking the result object.\n\nNote: To be able to get the inserted id, only one row can be inserted.\n\n\nExample\nInsert a record in the \"customers\" table, and return the ID:\n\n var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; var sql = \"INSERT INTO customers (name, address) \n VALUES ('Michelle', 'Blue Village 1')\"; \n con.query(sql, function (err, result) { if (err) throw err; console.log(\"1 record inserted, \n ID: \" + result.insertId); });});\nRun example »\n\nSave the code above in a file called \"demo_db_insert_id.js\", and run the file:\n\nRun \"demo_db_insert_id.js\"\n\nC:\\Users\\Your Name>node demo_db_insert_id.js\n\n\nWhich will give you something like this in return:\n\n\n 1 record inserted, ID: 15\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; console.log(\"Connected!\");\n var sql = \"INSERT INTO customers (name, address) \n VALUES ('Company Inc', 'Highway 37')\"; \n con.query(sql, function (err, result) { if (err) throw err; console.log(\"1 record inserted\"); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_insert.js" + }, + { + "language": "javascript", + "code": "Connected!1 record inserted" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\n con.connect(function(err) { if (err) throw err; \n console.log(\"Connected!\"); var sql = \"INSERT INTO customers (name, \n address) VALUES ?\"; var values = [ ['John', \n 'Highway 71'], ['Peter', 'Lowstreet 4'], \n ['Amy', 'Apple st 652'], ['Hannah', 'Mountain 21'], \n ['Michael', 'Valley 345'], ['Sandy', 'Ocean blvd 2'], \n ['Betty', 'Green Grass 1'], ['Richard', 'Sky st 331'], \n ['Susan', 'One way 98'], ['Vicky', 'Yellow Garden 2'], \n ['Ben', 'Park Lane 38'], ['William', 'Central st 954'], \n ['Chuck', 'Main Road 989'], ['Viola', 'Sideway 1633'] \n ]; con.query(sql, [values], function (err, result) \n { if (err) throw err; console.log(\"Number \n of records inserted: \" + result.affectedRows); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_insert_multiple.js" + }, + { + "language": "javascript", + "code": "Connected!Number of records inserted: 14" + }, + { + "language": "javascript", + "code": "{ fieldCount: 0, affectedRows: 14, insertId: 0, \n serverStatus: 2, warningCount: 0, message: '\\'Records:14 \n Duplicated: 0 Warnings: 0', protocol41: true, \n changedRows: 0}" + }, + { + "language": "javascript", + "code": "console.log(result.affectedRows)" + }, + { + "language": "javascript", + "code": "14" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", password: \"yourpassword\",\n database: \"mydb\"\n });con.connect(function(err) { if (err) throw err; var sql = \"INSERT INTO customers (name, address) \n VALUES ('Michelle', 'Blue Village 1')\"; \n con.query(sql, function (err, result) { if (err) throw err; console.log(\"1 record inserted, \n ID: \" + result.insertId); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_insert_id.js" + }, + { + "language": "javascript", + "code": "1 record inserted, ID: 15" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_select.asp", + "content": "Node.js MySQL Select From\n\n❮ Previous\nNext ❯\n\n\nSelecting From a Table\nTo select data from a table in MySQL, use the \"SELECT\" statement.\n\nExample\nSelect all records from the \"customers\" table, and display the result object:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers\", function (err, result, fields) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\n\nSELECT * will return all columns\n\nSave the code above in a file called \"demo_db_select.js\" and run the file:\n\nRun \"demo_db_select.js\"\n\nC:\\Users\\Your Name>node demo_db_select.js\n\n\nWhich will give you this result:\n\n\n [ { id: 1, name: 'John', address: 'Highway 71'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 3, name: 'Amy', \n address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 7, \n name: 'Betty', address: 'Green Grass 1'}, { id: 8, name: 'Richard', \n address: 'Sky st 331'}, { id: 9, name: 'Susan', address: 'One way \n 98'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, \n { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 12, name: 'William', \n address: 'Central st 954'}, { id: 13, name: 'Chuck', address: \n 'Main Road 989'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}]\n\n\n\n\n\n\n\nSelecting Columns\nTo select only some of the columns in a table, use the \"SELECT\" statement followed by the column name.\n\nExample\nSelect name and address from the \"customers\" table, and display the return object:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT name, address FROM customers\", function (err, result, fields) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_select2.js\" and run the file:\n\nRun \"demo_db_select2.js\"\n\nC:\\Users\\Your Name>node demo_db_select2.js\n\n\nWhich will give you this result:\n\n\n [ { name: 'John', address: 'Highway 71'}, { name: 'Peter', address: 'Lowstreet 4'}, { name: 'Amy', \n address: 'Apple st 652'}, { name: 'Hannah', address: \n 'Mountain 21'}, { name: 'Michael', address: 'Valley 345'}, \n { name: 'Sandy', address: 'Ocean blvd 2'}, { \n name: 'Betty', address: 'Green Grass 1'}, { name: 'Richard', \n address: 'Sky st 331'}, { name: 'Susan', address: 'One way \n 98'}, { name: 'Vicky', address: 'Yellow Garden 2'}, \n { name: 'Ben', address: 'Park Lane 38'}, { name: 'William', \n address: 'Central st 954'}, { name: 'Chuck', address: \n 'Main Road 989'}, { name: 'Viola', address: 'Sideway \n 1633'}]\n\n\nThe Result Object\nAs you can see from the result of the example above, the result object is an \narray containing each row as an object.\nTo return e.g. the address of the third record, just refer to the third array \nobject's address property:\n\nExample\nReturn the address of the third record:\n\n console.log(result[2].address);\n\nWhich will produce this result:\n\n\n Apple st 652\n\n\nThe Fields Object\nThe third parameter of the callback function is an array containing \ninformation about each field in the result.\n\nExample\nSelect all records from the \"customers\" table, and display the fields object:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT name, address FROM customers\", function (err, \n result, fields) { \n if (err) throw err; console.log(fields); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_select_fields.js\" and run the file:\n\nRun \"demo_db_select_fields.js\"\n\nC:\\Users\\Your Name>node demo_db_select_fields.js\n\n\nWhich will give you this result:\n\n\n [ { catalog: 'def', db: \n 'mydb', table: 'customers', \n orgTable: 'customers', name: 'name', \n orgName: 'name', charsetNr: 33, \n length: 765, type: 253, flags: 0, \n decimals: 0, default: undefined, \n zeroFill: false, protocol41: true }, { catalog: 'def', db: 'mydb', \n table: 'customers', orgTable: 'customers', \n name: 'address', orgName: 'address', \n charsetNr: 33, length: 765, type: \n 253, flags: 0, decimals: 0, \n default: undefined, zeroFill: false, \n protocol41: true }]\n\nAs you can see from the result of the example above, the fields object is an \narray containing information about each field as an object.\nTo return e.g. the name of the second field, just refer to the second array item's name property:\n\nExample\nReturn the name of the second field:\n\n console.log(fields[1].name);\n\nWhich will produce this result:\n\n\n address\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers\", function (err, result, fields) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_select.js" + }, + { + "language": "javascript", + "code": "[ { id: 1, name: 'John', address: 'Highway 71'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 3, name: 'Amy', \n address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 7, \n name: 'Betty', address: 'Green Grass 1'}, { id: 8, name: 'Richard', \n address: 'Sky st 331'}, { id: 9, name: 'Susan', address: 'One way \n 98'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, \n { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 12, name: 'William', \n address: 'Central st 954'}, { id: 13, name: 'Chuck', address: \n 'Main Road 989'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}]" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT name, address FROM customers\", function (err, result, fields) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_select2.js" + }, + { + "language": "javascript", + "code": "[ { name: 'John', address: 'Highway 71'}, { name: 'Peter', address: 'Lowstreet 4'}, { name: 'Amy', \n address: 'Apple st 652'}, { name: 'Hannah', address: \n 'Mountain 21'}, { name: 'Michael', address: 'Valley 345'}, \n { name: 'Sandy', address: 'Ocean blvd 2'}, { \n name: 'Betty', address: 'Green Grass 1'}, { name: 'Richard', \n address: 'Sky st 331'}, { name: 'Susan', address: 'One way \n 98'}, { name: 'Vicky', address: 'Yellow Garden 2'}, \n { name: 'Ben', address: 'Park Lane 38'}, { name: 'William', \n address: 'Central st 954'}, { name: 'Chuck', address: \n 'Main Road 989'}, { name: 'Viola', address: 'Sideway \n 1633'}]" + }, + { + "language": "javascript", + "code": "console.log(result[2].address);" + }, + { + "language": "javascript", + "code": "Apple st 652" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT name, address FROM customers\", function (err, \n result, fields) { \n if (err) throw err; console.log(fields); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_select_fields.js" + }, + { + "language": "javascript", + "code": "[ { catalog: 'def', db: \n 'mydb', table: 'customers', \n orgTable: 'customers', name: 'name', \n orgName: 'name', charsetNr: 33, \n length: 765, type: 253, flags: 0, \n decimals: 0, default: undefined, \n zeroFill: false, protocol41: true }, { catalog: 'def', db: 'mydb', \n table: 'customers', orgTable: 'customers', \n name: 'address', orgName: 'address', \n charsetNr: 33, length: 765, type: \n 253, flags: 0, decimals: 0, \n default: undefined, zeroFill: false, \n protocol41: true }]" + }, + { + "language": "javascript", + "code": "console.log(fields[1].name);" + }, + { + "language": "javascript", + "code": "address" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_where.asp", + "content": "Node.js MySQL Where\n\n❮ Previous\nNext ❯\n\n\nSelect With a Filter\nWhen selecting records from a table, you can filter the selection by using \nthe \"WHERE\" statement:\n\nExample\nSelect record(s) with the address \"Park Lane 38\":\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers WHERE address = 'Park Lane 38'\", function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_where.js\" and run the file:\n\nRun \"demo_db_where.js\"\n\nC:\\Users\\Your Name>node demo_db_where.js\n\n\nWhich will give you this result:\n\n\n [ { id: 11, name: 'Ben', address: 'Park Lane 38'}]\n\n\n\n\n\n\n\nWildcard Characters\nYou can also select the records that starts, includes, or ends with a given letter \nor phrase.\nUse the '%' wildcard to represent zero, one or multiple characters:\n\nExample\nSelect records where the address starts with the letter 'S':\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers WHERE address LIKE 'S%'\", function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_where_s.js\" and run the file:\n\nRun \"demo_db_where_s.js\"\n\nC:\\Users\\Your Name>node demo_db_where_s.js\n\n\nWhich will give you this result:\n\n\n [ { id: 8, name: 'Richard', \n address: 'Sky st 331'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}]\n\n\nEscaping Query Values\nWhen query values are variables provided by the user, you should escape the values.\nThis is to prevent SQL injections, which is a common web hacking technique to \ndestroy or misuse your database.\nThe MySQL module has methods to escape query values:\n\nExample\nEscape query values by using the mysql.escape() \nmethod:\n\n var adr = 'Mountain 21';var sql = 'SELECT * FROM customers WHERE address = \n ' + mysql.escape(adr);con.query(sql, function (err, result) { \n if (err) throw err; console.log(result);});\nRun example »\n\nYou can also use a ? as a placeholder for \nthe values you want to escape.\nIn this case, the variable is sent as the second parameter in the query() \nmethod:\n\nExample\nEscape query values by using the placeholder ? \nmethod:\n\n var adr = 'Mountain 21';var sql = 'SELECT * FROM customers WHERE address = \n ?';con.query(sql, [adr], function (err, result) { \n if (err) throw err; console.log(result);});\nRun example »\n\nIf you have multiple placeholders, the array contains multiple values, in \nthat order:\n\nExample\nMultiple placeholders:\n\n var name = 'Amy';var adr = 'Mountain 21';var sql = 'SELECT * FROM \n customers WHERE name = ? OR address = ?';con.query(sql, [name, adr], function (err, result) { \n if (err) throw err; console.log(result);});\nRun example »\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers WHERE address = 'Park Lane 38'\", function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_where.js" + }, + { + "language": "javascript", + "code": "[ { id: 11, name: 'Ben', address: 'Park Lane 38'}]" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers WHERE address LIKE 'S%'\", function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_where_s.js" + }, + { + "language": "javascript", + "code": "[ { id: 8, name: 'Richard', \n address: 'Sky st 331'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}]" + }, + { + "language": "javascript", + "code": "var adr = 'Mountain 21';var sql = 'SELECT * FROM customers WHERE address = \n ' + mysql.escape(adr);con.query(sql, function (err, result) { \n if (err) throw err; console.log(result);});" + }, + { + "language": "javascript", + "code": "var adr = 'Mountain 21';var sql = 'SELECT * FROM customers WHERE address = \n ?';con.query(sql, [adr], function (err, result) { \n if (err) throw err; console.log(result);});" + }, + { + "language": "javascript", + "code": "var name = 'Amy';var adr = 'Mountain 21';var sql = 'SELECT * FROM \n customers WHERE name = ? OR address = ?';con.query(sql, [name, adr], function (err, result) { \n if (err) throw err; console.log(result);});" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_orderby.asp", + "content": "Node.js MySQL Order By\n\n❮ Previous\nNext ❯\n\n\nSort the Result\nUse the ORDER BY statement to sort the result in ascending or descending \norder.\nThe ORDER BY keyword sorts the result ascending by default. To sort the \nresult in descending order, use the DESC keyword.\n\nExample\nSort the result alphabetically by name:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers ORDER BY name\", function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_orderby.js\" and run the file:\n\nRun \"demo_db_orderby.js\"\n\nC:\\Users\\Your Name>node demo_db_orderby.js\n\n\nWhich will give you this result:\n\n\n [ { id: 3, name: 'Amy', \n address: 'Apple st 652'}, \n { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 7, \n name: 'Betty', address: 'Green Grass 1'}, { id: 13, name: 'Chuck', address: \n 'Main Road 989'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 1, name: 'John', address: 'Higheay 71'}, { id: 5, name: 'Michael', address: 'Valley 345'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 8, name: 'Richard', \n address: 'Sky st 331'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 9, name: 'Susan', address: 'One way \n 98'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}, { id: 12, name: 'William', \n address: 'Central st 954'}]\n\n\n\n\n\n\n\nORDER BY DESC\nUse the DESC keyword to sort the result in a descending order.\n\nExample\nSort the result reverse alphabetically by name:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers ORDER BY name DESC\", function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_orderby_desc.js\" and run the file:\n\nRun \"demo_db_orderby_desc.js\"\n\nC:\\Users\\Your Name>node demo_db_orderby_desc.js\n\n\nWhich will give you this result:\n\n\n [ { id: 12, name: 'William', \n address: 'Central st 954'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, { id: 9, name: 'Susan', address: 'One way \n 98'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 8, name: 'Richard', \n address: 'Sky st 331'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 5, name: 'Michael', address: 'Valley 345'}, { id: 1, name: 'John', address: 'Higheay 71'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 13, name: 'Chuck', address: \n 'Main Road 989'}, { id: 7, \n name: 'Betty', address: 'Green Grass 1'}, \n { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 3, name: 'Amy', \n address: 'Apple st 652'}]\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers ORDER BY name\", function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_orderby.js" + }, + { + "language": "javascript", + "code": "[ { id: 3, name: 'Amy', \n address: 'Apple st 652'}, \n { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 7, \n name: 'Betty', address: 'Green Grass 1'}, { id: 13, name: 'Chuck', address: \n 'Main Road 989'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 1, name: 'John', address: 'Higheay 71'}, { id: 5, name: 'Michael', address: 'Valley 345'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 8, name: 'Richard', \n address: 'Sky st 331'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 9, name: 'Susan', address: 'One way \n 98'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}, { id: 12, name: 'William', \n address: 'Central st 954'}]" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n con.query(\"SELECT * FROM customers ORDER BY name DESC\", function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_orderby_desc.js" + }, + { + "language": "javascript", + "code": "[ { id: 12, name: 'William', \n address: 'Central st 954'}, { id: 14, name: 'Viola', address: 'Sideway \n 1633'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, { id: 9, name: 'Susan', address: 'One way \n 98'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 8, name: 'Richard', \n address: 'Sky st 331'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 5, name: 'Michael', address: 'Valley 345'}, { id: 1, name: 'John', address: 'Higheay 71'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 13, name: 'Chuck', address: \n 'Main Road 989'}, { id: 7, \n name: 'Betty', address: 'Green Grass 1'}, \n { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 3, name: 'Amy', \n address: 'Apple st 652'}]" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_delete.asp", + "content": "Node.js MySQL Delete\n\n❮ Previous\nNext ❯\n\n\nDelete Record\nYou can delete records from an existing table by using \nthe \"DELETE FROM\" statement:\n\nExample\nDelete any record with the address \"Mountain 21\":\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"DELETE FROM customers WHERE address = 'Mountain 21'\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(\"Number of records \n deleted: \" + result.affectedRows); });\n });\nRun example »\n\n\nNotice the WHERE clause in the DELETE syntax: The WHERE clause \nspecifies which record or records that should be deleted. If you omit the WHERE \nclause, all records will be deleted!\n\nSave the code above in a file called \"demo_db_delete.js\" and run the file:\n\nRun \"demo_db_delete.js\"\n\nC:\\Users\\Your Name>node demo_db_delete.js\n\n\nWhich will give you this result:\n\n\n Number of records deleted: 1\n\n\n\n\n\n\n\nThe Result Object\nWhen executing a query, a result object is returned.\nThe result object contains information about how the query \naffected the table.\nThe result object returned from the example above looks like this:\n\n\n { fieldCount: 0, affectedRows: 1, insertId: 0, \n serverStatus: 34, warningCount: 0, message: '', protocol41: true, \n changedRows: 0}\n\nThe values of the properties can be displayed like this:\n\nExample\nReturn the number of affected rows:\n\nconsole.log(result.affectedRows)\n\n\nWhich will produce this result:\n\n\n 1\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"DELETE FROM customers WHERE address = 'Mountain 21'\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(\"Number of records \n deleted: \" + result.affectedRows); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_delete.js" + }, + { + "language": "javascript", + "code": "Number of records deleted: 1" + }, + { + "language": "javascript", + "code": "{ fieldCount: 0, affectedRows: 1, insertId: 0, \n serverStatus: 34, warningCount: 0, message: '', protocol41: true, \n changedRows: 0}" + }, + { + "language": "javascript", + "code": "console.log(result.affectedRows)" + }, + { + "language": "javascript", + "code": "1" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_drop_table.asp", + "content": "Node.js MySQL Drop Table\n\n❮ Previous\nNext ❯\n\n\nDelete a Table\nYou can delete an existing table by using \nthe \"DROP TABLE\" statement:\n\nExample\nDelete the table \"customers\":\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"DROP TABLE customers\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(\"Table deleted\"); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_drop_table.js\" and run the file:\n\nRun \"demo_db_drop_table.js\"\n\nC:\\Users\\Your Name>node demo_db_drop_table.js\n\n\nWhich will give you this result:\n\n\n Table deleted\n\n\n\n\n\n\n\nDrop Only if Exist\nIf the the table you want to delete is already deleted, or for any other \nreason does not exist, you can use the IF EXISTS keyword to avoid getting an \nerror.\n\nExample\nDelete the table \"customers\" if it exists:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"DROP TABLE IF EXISTS customers\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_drop_table_if.js\" and run the file:\n\nRun \"demo_db_drop_table_if.js\"\n\nC:\\Users\\Your Name>node demo_db_drop_table_if.js\n\n\nIf the table exist, the result object will look like this:\n\n\n { fieldCount: 0, affectedRows: 0, insertId: 0, \n serverstatus: 2, warningCount: 0, message: '', \n protocol41: true, changedRows: 0}\n\nIf the table does not exist, the result object will look like this:\n\n\n { fieldCount: 0, affectedRows: 0, insertId: 0, \n serverstatus: 2, warningCount: 1, message: '', \n protocol41: true, changedRows: 0}\n\nAs you can see the only differnce is that the warningCount property is set to 1 if the table does not exist.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"DROP TABLE customers\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(\"Table deleted\"); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_drop_table.js" + }, + { + "language": "javascript", + "code": "Table deleted" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"DROP TABLE IF EXISTS customers\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_drop_table_if.js" + }, + { + "language": "javascript", + "code": "{ fieldCount: 0, affectedRows: 0, insertId: 0, \n serverstatus: 2, warningCount: 0, message: '', \n protocol41: true, changedRows: 0}" + }, + { + "language": "javascript", + "code": "{ fieldCount: 0, affectedRows: 0, insertId: 0, \n serverstatus: 2, warningCount: 1, message: '', \n protocol41: true, changedRows: 0}" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_update.asp", + "content": "Node.js MySQL Update\n\n❮ Previous\nNext ❯\n\n\nUpdate Table\nYou can update existing records in a table by using \nthe \"UPDATE\" statement:\n\nExample\nOverwrite the address column from \"Valley 345\" to \"Canyon 123\":\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"UPDATE customers SET address = 'Canyon 123' WHERE address = \n 'Valley 345'\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result.affectedRows + \" \n record(s) updated\"); });\n });\nRun example »\n\n\nNotice the WHERE clause in the UPDATE syntax: The WHERE clause \nspecifies which record or records that should be updated. If you omit the WHERE \nclause, all records will be updated!\n\nSave the code above in a file called \"demo_db_update.js\" and run the file:\n\nRun \"demo_db_update.js\"\n\nC:\\Users\\Your Name>node demo_db_update.js\n\n\nWhich will give you this result:\n\n\n 1 record(s) updated\n\n\n\n\n\n\n\nThe Result Object\nWhen executing a query, a result object is returned.\nThe result object contains information about how the query \naffected the table.\nThe result object returned from the example above looks like this:\n\n\n { fieldCount: 0, affectedRows: 1, insertId: 0, \n serverStatus: 34, warningCount: 0, message: '(Rows \n matched: 1 Changed: 1 Warnings: 0', protocol41: true, \n changedRows: 1}\n\nThe values of the properties can be displayed like this:\n\nExample\nReturn the number of affected rows:\n\nconsole.log(result.affectedRows)\n\n\nWhich will produce this result:\n\n\n 1\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"UPDATE customers SET address = 'Canyon 123' WHERE address = \n 'Valley 345'\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result.affectedRows + \" \n record(s) updated\"); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_update.js" + }, + { + "language": "javascript", + "code": "1 record(s) updated" + }, + { + "language": "javascript", + "code": "{ fieldCount: 0, affectedRows: 1, insertId: 0, \n serverStatus: 34, warningCount: 0, message: '(Rows \n matched: 1 Changed: 1 Warnings: 0', protocol41: true, \n changedRows: 1}" + }, + { + "language": "javascript", + "code": "console.log(result.affectedRows)" + }, + { + "language": "javascript", + "code": "1" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_limit.asp", + "content": "Node.js MySQL Limit\n\n❮ Previous\nNext ❯\n\n\nLimit the Result\nYou can limit the number of records returned from the query, by using the \"LIMIT\" statement:\n\nExample\nSelect the 5 first records in the \"customers\" table:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"SELECT * FROM customers LIMIT 5\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\nSave the code above in a file called \"demo_db_limit.js\" and run the file:\n\nRun \"demo_db_limit.js\"\n\nC:\\Users\\Your Name>node demo_db_limit.js\n\n\nWhich will give you this result:\n\n\n [ { id: 1, name: 'John', address: 'Highway 71'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 3, name: 'Amy', \n address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}]\n\n\n\n\n\n\n\nStart From Another Position\nIf you want to return five records, starting from the third record, you \ncan use the \"OFFSET\" keyword:\n\nExample\nStart from position 3, and return the next 5 records:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"SELECT * FROM customers LIMIT 5 OFFSET 2\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\n\nNote: \"OFFSET 2\", means starting from the third position, \nnot the second!\n\nSave the code above in a file called \"demo_db_offset.js\" and run the file:\n\nRun \"demo_db_offset.js\"\n\nC:\\Users\\Your Name>node demo_db_offset.js\n\n\nWhich will give you this result:\n\n\n [ { id: 3, name: 'Amy', \n address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 7, name: 'Betty', \n address: 'Green Grass 1'}]\n\n\nShorter Syntax\nYou can also write your SQL statement like this \"LIMIT 2, 5\" which \nreturns the same as the offset example above:\n\nExample\nStart from position 3, and return the next 5 records:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"SELECT * FROM customers LIMIT 2, 5\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\n\nNote: The numbers are reversed: \"LIMIT 2, 5\" is the \n same as \"LIMIT 5 OFFSET 2\"\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"SELECT * FROM customers LIMIT 5\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_limit.js" + }, + { + "language": "javascript", + "code": "[ { id: 1, name: 'John', address: 'Highway 71'}, { id: \n 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 3, name: 'Amy', \n address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}]" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"SELECT * FROM customers LIMIT 5 OFFSET 2\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_offset.js" + }, + { + "language": "javascript", + "code": "[ { id: 3, name: 'Amy', \n address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: \n 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}, \n { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 7, name: 'Betty', \n address: 'Green Grass 1'}]" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; \n var sql = \"SELECT * FROM customers LIMIT 2, 5\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mysql_join.asp", + "content": "Node.js MySQL Join\n\n❮ Previous\nNext ❯\n\n\nJoin Two or More Tables\nYou can combine rows from two or more tables, based on a related column \nbetween them, by using a JOIN statement.\nConsider you have a \"users\" table and a \"products\" table:\n\nusers\n[ { id: 1, name: 'John', \n favorite_product: 154}, { id: \n 2, name: 'Peter', favorite_product: 154}, { id: 3, name: 'Amy', \n favorite_product: 155}, { id: 4, name: 'Hannah', favorite_product:}, { id: 5, name: 'Michael', \n favorite_product:}]\n\n\nproducts\n[ { id: 154, name: \n 'Chocolate Heaven' }, { id: 155, name: 'Tasty Lemons' }, { \n id: 156, name: 'Vanilla Dreams' }]\n\nThese two tables can be combined by using users' favorite_product field and products' \nid field.\n\nExample\nSelect records with a match in both tables:\n\n var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; var \n sql = \"SELECT users.name AS user, products.name AS favorite FROM users \n JOIN products ON \n users.favorite_product = products.id\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });\nRun example »\n\n\nNote: You can use INNER JOIN instead of JOIN. They will \n both give you the same result.\n\nSave the code above in a file called \"demo_db_join.js\" and run the file:\n\nRun \"demo_db_join.js\"\n\nC:\\Users\\Your Name>node demo_db_join.js\n\n\nWhich will give you this result:\n\n[ { user: 'John', favorite: \n 'Chocolate Heaven' }, { user: 'Peter', favorite: 'Chocolate Heaven' }, { \n user: 'Amy', favorite: 'Tasty Lemons' }]\n\nAs you can see from the result above, only the records with a match in both \ntables are returned.\n\n\n\n\n\n\nLeft Join\nIf you want to return all users, no matter if they have a favorite product or \nnot, use the LEFT JOIN statement:\n\nExample\nSelect all users and their favorite product:\n\n SELECT users.name AS user,products.name AS favoriteFROM usersLEFT\n JOIN products ON users.favorite_product = products.id\nRun example »\n\nWhich will give you this result:\n\n[ { user: 'John', favorite: \n 'Chocolate Heaven' }, { user: 'Peter', favorite: 'Chocolate Heaven' }, { \n user: 'Amy', favorite: 'Tasty Lemons' }, { \n user: 'Hannah', favorite: null }, { user: 'Michael', favorite: null }]\n\n\nRight Join\nIf you want to return all products, and the users who have them as their \nfavorite, even if no user have them as their favorite, use the RIGHT JOIN \nstatement:\n\nExample\nSelect all products and the user who have them as their favorite:\n\n SELECT users.name AS user,products.name AS favoriteFROM usersRIGHT\n JOIN products ON users.favorite_product = products.id\nRun example »\n\nWhich will give you this result:\n\n[ { user: 'John', favorite: \n 'Chocolate Heaven' }, { user: 'Peter', favorite: 'Chocolate Heaven' }, { \n user: 'Amy', favorite: 'Tasty Lemons' }, { \n user: null, favorite: 'Vanilla Dreams' }]\n\n\nNote: Hannah and Michael, who have no favorite product, are not included in the result.\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "[ { id: 1, name: 'John', \n favorite_product: 154}, { id: \n 2, name: 'Peter', favorite_product: 154}, { id: 3, name: 'Amy', \n favorite_product: 155}, { id: 4, name: 'Hannah', favorite_product:}, { id: 5, name: 'Michael', \n favorite_product:}]" + }, + { + "language": "javascript", + "code": "[ { id: 154, name: \n 'Chocolate Heaven' }, { id: 155, name: 'Tasty Lemons' }, { \n id: 156, name: 'Vanilla Dreams' }]" + }, + { + "language": "javascript", + "code": "var mysql = require('mysql');\n var con = mysql.createConnection({ \n host: \"localhost\", user: \"yourusername\", \n password: \"yourpassword\", database: \"mydb\"});\ncon.connect(function(err) { if (err) throw err; var \n sql = \"SELECT users.name AS user, products.name AS favorite FROM users \n JOIN products ON \n users.favorite_product = products.id\"; \n con.query(sql, function (err, result) { \n if (err) throw err; console.log(result); });\n });" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_db_join.js" + }, + { + "language": "javascript", + "code": "[ { user: 'John', favorite: \n 'Chocolate Heaven' }, { user: 'Peter', favorite: 'Chocolate Heaven' }, { \n user: 'Amy', favorite: 'Tasty Lemons' }]" + }, + { + "language": "javascript", + "code": "SELECT users.name AS user,products.name AS favoriteFROM usersLEFT\n JOIN products ON users.favorite_product = products.id" + }, + { + "language": "javascript", + "code": "[ { user: 'John', favorite: \n 'Chocolate Heaven' }, { user: 'Peter', favorite: 'Chocolate Heaven' }, { \n user: 'Amy', favorite: 'Tasty Lemons' }, { \n user: 'Hannah', favorite: null }, { user: 'Michael', favorite: null }]" + }, + { + "language": "javascript", + "code": "SELECT users.name AS user,products.name AS favoriteFROM usersRIGHT\n JOIN products ON users.favorite_product = products.id" + }, + { + "language": "javascript", + "code": "[ { user: 'John', favorite: \n 'Chocolate Heaven' }, { user: 'Peter', favorite: 'Chocolate Heaven' }, { \n user: 'Amy', favorite: 'Tasty Lemons' }, { \n user: null, favorite: 'Vanilla Dreams' }]" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb.asp", + "content": "Node.js MongoDB\n\n❮ Previous\nNext ❯\n\n\nNode.js can be used in database applications.\nOne of the most popular NoSQL database is MongoDB.\n\nMongoDB\nTo be able to experiment with the code examples, you will need access to a MongoDB database.\nYou can download a free MongoDB database at\nhttps://www.mongodb.com.\nOr get started right away with a MongoDB cloud service at \nhttps://www.mongodb.com/cloud/atlas.\n\nInstall MongoDB Driver\nLet us try to access a MongoDB database with Node.js.\nTo download and install the official MongoDB driver, open the Command Terminal and execute the following:\n\nDownload and install mongodb package:\n\nC:\\Users\\Your Name>npm install mongodb\n\n\nNow you have downloaded and installed a mongodb database driver.\nNode.js can use this module to manipulate MongoDB databases:\n\n\n var mongo = require('mongodb');\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "C:\\Users\\Your Name>npm install mongodb" + }, + { + "language": "javascript", + "code": "var mongo = require('mongodb');" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_create_db.asp", + "content": "Node.js MongoDB Create Database\n\n❮ Previous\nNext ❯\n\n\nCreating a Database\nTo create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the \ncorrect ip address and the name of the database you want to create.\nMongoDB will create the database if it does not exist, and make a connection \nto it.\n\nExample\nCreate a database called \"mydb\":\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/mydb\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; console.log(\"Database \n created!\"); db.close();});\nRun example »\n\nSave the code above in a file called \"demo_create_mongo_db.js\" and run the file:\n\nRun \"demo_create_mongo_db.js\"\n\nC:\\Users\\Your Name>node demo_create_mongo_db.js\n\n\nWhich will give you this result:\n\n\n Database created!\n\n\nImportant: In MongoDB, a database is not created until it \n gets content!\n\nMongoDB waits until you have created a collection (table), with at least one document (record) before it actually creates the database (and collection).\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/mydb\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; console.log(\"Database \n created!\"); db.close();});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_create_mongo_db.js" + }, + { + "language": "javascript", + "code": "Database created!" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_createcollection.asp", + "content": "Node.js MongoDB Create Collection\n\n❮ Previous\nNext ❯\n\n\n\nA collection in MongoDB is the same as a table in MySQL\n\nCreating a Collection\nTo create a collection in MongoDB, use the createCollection() method:\n\nExample\nCreate a collection called \"customers\":\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n dbo.createCollection(\"customers\", \n function(err, res) { if (err) throw err; console.log(\"Collection created!\"); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_createcollection.js\" and run the file:\n\nRun \"demo_mongodb_createcollection.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_createcollection.js\n\n\nWhich will give you this result:\n\n\n Collection created!\n\n\nImportant: In MongoDB, a collection is not created until it \n gets content!\n\nMongoDB waits until you have inserted a document before it actually creates the collection.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n dbo.createCollection(\"customers\", \n function(err, res) { if (err) throw err; console.log(\"Collection created!\"); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_createcollection.js" + }, + { + "language": "javascript", + "code": "Collection created!" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_insert.asp", + "content": "Node.js MongoDB Insert\n\n❮ Previous\nNext ❯\n\n\nInsert Into Collection\nTo insert a record, or document as it is called in MongoDB, into a collection, we use the \ninsertOne() method.\n\nA document in MongoDB is the same as a record in MySQL\n\nThe first parameter of the insertOne() method is an object containing the \nname(s) and value(s) of each field in the document you want to insert.\nIt also takes a callback function where you can work with any errors, or the \nresult of the insertion:\n\nExample\nInsert a document in the \"customers\" collection:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myobj = { name: \"Company \n Inc\", address: \"Highway 37\" }; dbo.collection(\"customers\").insertOne(myobj, function(err, res) {\n if (err) throw err; console.log(\"1 \n document \n inserted\"); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_insert.js\" and run the file:\n\nRun \"demo_mongodb_insert.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_insert.js\n\n\nWhich will give you this result:\n\n\n 1 document inserted\n\n\nNote: If you try to insert documents in a collection that do not \nexist, MongoDB will create the collection automatically.\n\n\n\n\n\n\n\nInsert Multiple Documents\nTo insert multiple documents into a collection in MongoDB, we use the \ninsertMany() method.\nThe first parameter of the insertMany() method \nis an array of objects, containing the data you want to \ninsert.\nIt also takes a callback function where you can work with any errors, or the \nresult of the insertion:\n\nExample\nInsert multiple documents in the \"customers\" collection:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myobj = [ { name: 'John', address: 'Highway 71'}, \n { name: 'Peter', address: 'Lowstreet 4'}, { name: 'Amy', \n address: 'Apple st 652'}, { name: 'Hannah', address: \n 'Mountain 21'}, { name: 'Michael', address: 'Valley \n 345'}, { name: 'Sandy', address: 'Ocean blvd 2'}, \n { name: 'Betty', address: 'Green Grass 1'}, { name: \n 'Richard', address: 'Sky st 331'}, { name: 'Susan', \n address: 'One way 98'}, { name: 'Vicky', address: \n 'Yellow Garden 2'}, { name: 'Ben', address: 'Park Lane \n 38'}, { name: 'William', address: 'Central st 954'}, \n { name: 'Chuck', address: 'Main Road 989'}, { name: \n 'Viola', address: 'Sideway 1633'} ]; dbo.collection(\"customers\").insertMany(myobj, \n function(err, res) { if (err) throw err; \n console.log(\"Number of documents inserted: \" + res.insertedCount); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_insert_multiple.js\" and run the file:\n\nRun \"demo_mongodb_insert_multiple.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_insert_multiple.js\n\n\nWhich will give you this result:\n\n\n Number of documents inserted: 14\n\n\nThe Result Object\nWhen executing the insertMany() method, a result object is returned.\nThe result object contains information about how the insertion affected the \ndatabase.\nThe object returned from the example above looked like this:\n\n\n { result: { ok: 1, n: 14 }, ops: [ { \n name: 'John', address: 'Highway 71', _id: 58fdbf5c0ef8a50b4cdd9a84 }, \n { name: 'Peter', address: 'Lowstreet 4', _id: 58fdbf5c0ef8a50b4cdd9a85 }, \n { name: 'Amy', address: 'Apple st 652', _id: 58fdbf5c0ef8a50b4cdd9a86 }, \n { name: 'Hannah', address: 'Mountain 21', _id: 58fdbf5c0ef8a50b4cdd9a87 }, \n { name: 'Michael', address: 'Valley 345', _id: 58fdbf5c0ef8a50b4cdd9a88 }, \n { name: 'Sandy', address: 'Ocean blvd 2', _id: 58fdbf5c0ef8a50b4cdd9a89 }, \n { name: 'Betty', address: 'Green Grass 1', _id: 58fdbf5c0ef8a50b4cdd9a8a }, \n { name: 'Richard', address: 'Sky st 331', _id: 58fdbf5c0ef8a50b4cdd9a8b }, \n { name: 'Susan', address: 'One way 98', _id: 58fdbf5c0ef8a50b4cdd9a8c }, \n { name: 'Vicky', address: 'Yellow Garden 2', _id: 58fdbf5c0ef8a50b4cdd9a8d }, \n { name: 'Ben', address: 'Park Lane 38', _id: 58fdbf5c0ef8a50b4cdd9a8e }, \n { name: 'William', address: 'Central st 954', _id: 58fdbf5c0ef8a50b4cdd9a8f }, \n { name: 'Chuck', address: 'Main Road 989', _id: 58fdbf5c0ef8a50b4cdd9a90 }, \n { name: 'Viola', address: 'Sideway 1633', _id: 58fdbf5c0ef8a50b4cdd9a91 } ], \n insertedCount: 14, insertedIds: [ \n 58fdbf5c0ef8a50b4cdd9a84, 58fdbf5c0ef8a50b4cdd9a85, \n 58fdbf5c0ef8a50b4cdd9a86, 58fdbf5c0ef8a50b4cdd9a87, \n 58fdbf5c0ef8a50b4cdd9a88, 58fdbf5c0ef8a50b4cdd9a89, \n 58fdbf5c0ef8a50b4cdd9a8a, 58fdbf5c0ef8a50b4cdd9a8b, \n 58fdbf5c0ef8a50b4cdd9a8c, 58fdbf5c0ef8a50b4cdd9a8d, \n 58fdbf5c0ef8a50b4cdd9a8e, 58fdbf5c0ef8a50b4cdd9a8f \n 58fdbf5c0ef8a50b4cdd9a90, 58fdbf5c0ef8a50b4cdd9a91 ]\n }\n\nThe values of the properties can be displayed like this:\n\nExample\nReturn the number of inserted documents:\n\nconsole.log(res.insertedCount)\n\n\nWhich will produce this result:\n\n\n14\n\n\nThe _id Field\nIf you do not specify an _id field, then MongoDB \nwill add one for you and assign a unique id for each document.\nIn the example above no _id field was \nspecified, and as you can see from the result object, MongoDB assigned a unique \n_id for each document.\nIf you do specify the _id field, the value must \nbe unique for each document:\n\nExample\nInsert three records in a \"products\" table, with specified \n_id fields:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myobj = [ { _id: 154, name: \n 'Chocolate Heaven'}, { _id: 155, name: \n 'Tasty Lemon'}, { _id: 156, name: \n 'Vanilla Dream'} ]; dbo.collection(\"products\").insertMany(myobj, \n function(err, res) { if (err) throw err; \n console.log(res); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_insert_id.js\" and run the file:\n\nRun \"demo_mongodb_insert_id.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_insert_id.js\n\n\nWhich will give you this result:\n\n\n { result: { ok: 1, n: 3 }, ops: [ { \n _id: 154, name: 'Chocolate Heaven }, { \n _id: 155, name: 'Tasty Lemon }, { \n _id: 156, name: 'Vanilla Dream } ], \n insertedCount: 3, insertedIds: [ \n 154, 155, \n 156 ]\n }\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myobj = { name: \"Company \n Inc\", address: \"Highway 37\" }; dbo.collection(\"customers\").insertOne(myobj, function(err, res) {\n if (err) throw err; console.log(\"1 \n document \n inserted\"); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_insert.js" + }, + { + "language": "javascript", + "code": "1 document inserted" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myobj = [ { name: 'John', address: 'Highway 71'}, \n { name: 'Peter', address: 'Lowstreet 4'}, { name: 'Amy', \n address: 'Apple st 652'}, { name: 'Hannah', address: \n 'Mountain 21'}, { name: 'Michael', address: 'Valley \n 345'}, { name: 'Sandy', address: 'Ocean blvd 2'}, \n { name: 'Betty', address: 'Green Grass 1'}, { name: \n 'Richard', address: 'Sky st 331'}, { name: 'Susan', \n address: 'One way 98'}, { name: 'Vicky', address: \n 'Yellow Garden 2'}, { name: 'Ben', address: 'Park Lane \n 38'}, { name: 'William', address: 'Central st 954'}, \n { name: 'Chuck', address: 'Main Road 989'}, { name: \n 'Viola', address: 'Sideway 1633'} ]; dbo.collection(\"customers\").insertMany(myobj, \n function(err, res) { if (err) throw err; \n console.log(\"Number of documents inserted: \" + res.insertedCount); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_insert_multiple.js" + }, + { + "language": "javascript", + "code": "Number of documents inserted: 14" + }, + { + "language": "javascript", + "code": "{ result: { ok: 1, n: 14 }, ops: [ { \n name: 'John', address: 'Highway 71', _id: 58fdbf5c0ef8a50b4cdd9a84 }, \n { name: 'Peter', address: 'Lowstreet 4', _id: 58fdbf5c0ef8a50b4cdd9a85 }, \n { name: 'Amy', address: 'Apple st 652', _id: 58fdbf5c0ef8a50b4cdd9a86 }, \n { name: 'Hannah', address: 'Mountain 21', _id: 58fdbf5c0ef8a50b4cdd9a87 }, \n { name: 'Michael', address: 'Valley 345', _id: 58fdbf5c0ef8a50b4cdd9a88 }, \n { name: 'Sandy', address: 'Ocean blvd 2', _id: 58fdbf5c0ef8a50b4cdd9a89 }, \n { name: 'Betty', address: 'Green Grass 1', _id: 58fdbf5c0ef8a50b4cdd9a8a }, \n { name: 'Richard', address: 'Sky st 331', _id: 58fdbf5c0ef8a50b4cdd9a8b }, \n { name: 'Susan', address: 'One way 98', _id: 58fdbf5c0ef8a50b4cdd9a8c }, \n { name: 'Vicky', address: 'Yellow Garden 2', _id: 58fdbf5c0ef8a50b4cdd9a8d }, \n { name: 'Ben', address: 'Park Lane 38', _id: 58fdbf5c0ef8a50b4cdd9a8e }, \n { name: 'William', address: 'Central st 954', _id: 58fdbf5c0ef8a50b4cdd9a8f }, \n { name: 'Chuck', address: 'Main Road 989', _id: 58fdbf5c0ef8a50b4cdd9a90 }, \n { name: 'Viola', address: 'Sideway 1633', _id: 58fdbf5c0ef8a50b4cdd9a91 } ], \n insertedCount: 14, insertedIds: [ \n 58fdbf5c0ef8a50b4cdd9a84, 58fdbf5c0ef8a50b4cdd9a85, \n 58fdbf5c0ef8a50b4cdd9a86, 58fdbf5c0ef8a50b4cdd9a87, \n 58fdbf5c0ef8a50b4cdd9a88, 58fdbf5c0ef8a50b4cdd9a89, \n 58fdbf5c0ef8a50b4cdd9a8a, 58fdbf5c0ef8a50b4cdd9a8b, \n 58fdbf5c0ef8a50b4cdd9a8c, 58fdbf5c0ef8a50b4cdd9a8d, \n 58fdbf5c0ef8a50b4cdd9a8e, 58fdbf5c0ef8a50b4cdd9a8f \n 58fdbf5c0ef8a50b4cdd9a90, 58fdbf5c0ef8a50b4cdd9a91 ]\n }" + }, + { + "language": "javascript", + "code": "console.log(res.insertedCount)" + }, + { + "language": "javascript", + "code": "14" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myobj = [ { _id: 154, name: \n 'Chocolate Heaven'}, { _id: 155, name: \n 'Tasty Lemon'}, { _id: 156, name: \n 'Vanilla Dream'} ]; dbo.collection(\"products\").insertMany(myobj, \n function(err, res) { if (err) throw err; \n console.log(res); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_insert_id.js" + }, + { + "language": "javascript", + "code": "{ result: { ok: 1, n: 3 }, ops: [ { \n _id: 154, name: 'Chocolate Heaven }, { \n _id: 155, name: 'Tasty Lemon }, { \n _id: 156, name: 'Vanilla Dream } ], \n insertedCount: 3, insertedIds: [ \n 154, 155, \n 156 ]\n }" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp", + "content": "Node.js MongoDB Find\n\n❮ Previous\nNext ❯\n\n\n\nIn MongoDB we use the find and findOne methods to find data in a collection.\nJust like the SELECT statement is used to find data in a \n table in a MySQL database.\n\nFind One\nTo select data from a collection in MongoDB, we can use the\nfindOne() method.\nThe findOne() method returns the first \noccurrence in the selection.\nThe first parameter of the findOne() method \nis a query object. In this example we use an empty query object, which selects \nall documents in a collection (but returns only the first document).\n\nExample\nFind the first document in the customers collection:\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); dbo.collection(\"customers\").findOne({}, function(err, result) { if (err) throw err; console.log(result.name); db.close(); \n });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_findone.js\" and run the file:\n\nRun \"demo_mongodb_findone.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_findone.js\n\n\nWhich will give you this result:\n\nCompany Inc.\n\n\n\n\n\n\n\nFind All\nTo select data from a table in MongoDB, we can also use the\nfind() method.\nThe find() method returns all \noccurrences in the selection.\nThe first parameter of the find() method \nis a query object. In this example we use an empty query object, which selects \nall documents in the collection.\n\nNo parameters in the find() method gives you the same result as SELECT * in MySQL.\n\n\nExample\nFind all documents in the customers collection:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_find.js\" and run the file:\n\nRun \"demo_mongodb_find.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_find.js\n\n\nWhich will give you this result:\n\n[ { _id: \n 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', \n address: 'Apple st 652'}, { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a , \n name: 'Betty', address: 'Green Grass 1'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', \n address: 'Sky st 331'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way \n 98'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden 2'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', \n address: 'Central st 954'}, { _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: \n 'Main Road 989'}, { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway \n 1633'}]\n\n\nFind Some\nThe second parameter of the find() method \nis the projection object that describes which fields to include in the result.\nThis parameter is optional, and if omitted, all fields will be included in \nthe result.\n\nExample\nReturn the fields \"name\" and \"address\" of all documents in the customers collection:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { _id: 0, name: 1, address: \n 1 } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_find_fields.js\" and run the file:\n\nRun \"demo_mongodb_find_fields.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_find_fields.js\n\n\nWhich will give you this result:\n\n[ { name: 'John', address: 'Highway 71'}, { name: 'Peter', address: 'Lowstreet 4'}, { \n name: 'Amy', \n address: 'Apple st 652'}, { name: 'Hannah', address: \n 'Mountain 21'}, { name: 'Michael', address: 'Valley 345'}, \n { name: 'Sandy', address: 'Ocean blvd 2'}, { \n name: 'Betty', address: 'Green Grass 1'}, { name: 'Richard', \n address: 'Sky st 331'}, { name: 'Susan', address: 'One way \n 98'}, { name: 'Vicky', address: 'Yellow Garden 2'}, \n { name: 'Ben', address: 'Park Lane 38'}, { \n name: 'William', \n address: 'Central st 954'}, { name: 'Chuck', address: \n 'Main Road 989'}, { name: 'Viola', address: 'Sideway \n 1633'}]\n\n\nYou are not allowed to specify both 0 and 1 values in the same object (except \nif one of the fields is the _id field). If you specify a field with the value 0, all other fields get the value 1, \nand vice versa:\n\n\nExample\nThis example will exclude \"address\" from the result:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { address: 0 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\n\nTo exclude the _id field, you must set its value to 0:\n\n\nExample\nThis example will return only the \"name\" field:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { _id: 0, name: 1 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\n\nExample\nThis example will give you the same result as the first example; return all \nfields except the _id field:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { _id: 0 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\n\nExample\nYou get an error if you specify both 0 and 1 values in the same object \n(except if one of the fields is the _id field):\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { name: 1, address: 0 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\n\nThe Result Object\nAs you can see from the result of the example above, the result can be converted into an array containing each \ndocument as an object.\nTo return e.g. the address of the third document, just refer to the third array \nobject's address property:\n\nExample\nReturn the address of the third document:\n\n console.log(result[2].address);\n\nWhich will produce this result:\n\n\n Apple st 652\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); dbo.collection(\"customers\").findOne({}, function(err, result) { if (err) throw err; console.log(result.name); db.close(); \n });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_findone.js" + }, + { + "language": "javascript", + "code": "Company Inc." + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_find.js" + }, + { + "language": "javascript", + "code": "[ { _id: \n 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', \n address: 'Apple st 652'}, { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a , \n name: 'Betty', address: 'Green Grass 1'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', \n address: 'Sky st 331'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way \n 98'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden 2'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', \n address: 'Central st 954'}, { _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: \n 'Main Road 989'}, { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway \n 1633'}]" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { _id: 0, name: 1, address: \n 1 } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_find_fields.js" + }, + { + "language": "javascript", + "code": "[ { name: 'John', address: 'Highway 71'}, { name: 'Peter', address: 'Lowstreet 4'}, { \n name: 'Amy', \n address: 'Apple st 652'}, { name: 'Hannah', address: \n 'Mountain 21'}, { name: 'Michael', address: 'Valley 345'}, \n { name: 'Sandy', address: 'Ocean blvd 2'}, { \n name: 'Betty', address: 'Green Grass 1'}, { name: 'Richard', \n address: 'Sky st 331'}, { name: 'Susan', address: 'One way \n 98'}, { name: 'Vicky', address: 'Yellow Garden 2'}, \n { name: 'Ben', address: 'Park Lane 38'}, { \n name: 'William', \n address: 'Central st 954'}, { name: 'Chuck', address: \n 'Main Road 989'}, { name: 'Viola', address: 'Sideway \n 1633'}]" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { address: 0 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { _id: 0, name: 1 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { _id: 0 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find({}, { projection: { name: 1, address: 0 \n } }).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "console.log(result[2].address);" + }, + { + "language": "javascript", + "code": "Apple st 652" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_query.asp", + "content": "Node.js MongoDB Query\n\n❮ Previous\nNext ❯\n\n\nFilter the Result\nWhen finding documents in a collection, you can filter the result by using a \nquery object.\nThe first argument of the find() method \nis a query object, and is used to limit the search.\n\nExample\nFind documents with the address \"Park Lane 38\":\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var query = { address: \"Park Lane 38\" }; dbo.collection(\"customers\").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_query.js\" and run the file:\n\nRun \"demo_mongodb_query.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_query.js\n\n\nWhich will give you this result:\n\n[ { _id: 58fdbf5c0ef8a50b4cdd9a8e \n , name: 'Ben', address: 'Park Lane 38' }]\n\n\n\n\n\n\n\nFilter With Regular Expressions\nYou can write regular expressions to find exactly what you are searching for.\n\nRegular expressions can only be used to query strings.\n\nTo find only the documents where the \"address\" field starts with the letter \"S\", use the regular \nexpression /^S/:\n\nExample\nFind documents where the address starts with the letter \"S\":\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var query = { address: /^S/ }; dbo.collection(\"customers\").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_query_s.js\" and run the file:\n\nRun \"demo_mongodb_query_s.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_query_s.js\n\n\nWhich will give you this result:\n\n[ { _id: \n 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', \n address: 'Sky st 331' }, { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway \n 1633' }]\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var query = { address: \"Park Lane 38\" }; dbo.collection(\"customers\").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_query.js" + }, + { + "language": "javascript", + "code": "[ { _id: 58fdbf5c0ef8a50b4cdd9a8e \n , name: 'Ben', address: 'Park Lane 38' }]" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var query = { address: /^S/ }; dbo.collection(\"customers\").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_query_s.js" + }, + { + "language": "javascript", + "code": "[ { _id: \n 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', \n address: 'Sky st 331' }, { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway \n 1633' }]" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_sort.asp", + "content": "Node.js MongoDB Sort\n\n❮ Previous\nNext ❯\n\n\nSort the Result\nUse the sort() method to sort the result in ascending or descending order.\nThe sort() method takes one parameter, an \nobject defining the sorting order.\n\nExample\nSort the result alphabetically by name:\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var mysort = { name: 1 }; dbo.collection(\"customers\").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});\nRun example »\n\nSave the code above in a file called \"demo_sort.js\" and run the file:\n\nRun \"demo_sort.js\"\n\nC:\\Users\\Your Name>node demo_sort.js\n\n\nWhich will give you this result:\n\n[ { \n _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', \n address: 'Apple st 652'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a, \n name: 'Betty', address: 'Green Grass 1'}, { _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: \n 'Main Road 989'}, { _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: \n 'Mountain 21'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'}, { _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley 345'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', \n address: 'Sky st 331'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd 2'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way \n 98'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address: 'Yellow Garden 2'}, { _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway \n 1633'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8f, name: 'William', \n address: 'Central st 954'}]\n\n\n\n\n\n\n\nSort Descending\nUse the value -1 in the sort object to sort descending.\n\n{ name: 1 } // ascending{ name: -1 } // descending\n\n\nExample\nSort the result reverse alphabetically by name:\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var mysort = { name: -1 }; dbo.collection(\"customers\").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});\nRun example »\n\nSave the code above in a file called \"demo_sort_desc.js\" and run the file:\n\nRun \"demo_sort_desc.js\"\n\nC:\\Users\\Your Name>node demo_sort_desc.js\n\n\nWhich will give you this result:\n\n[ { \n _id: 58fdbf5c0ef8a50b4cdd9a8f, name: 'William', \n address: 'Central st 954'}, { _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway \n 1633'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address: 'Yellow Garden 2'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way \n 98'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd 2'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', \n address: 'Sky st 331'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'}, { _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley 345'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'}, { _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: \n 'Main Road 989'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a, \n name: 'Betty', address: 'Green Grass 1'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', \n address: 'Apple st 652'}]\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var mysort = { name: 1 }; dbo.collection(\"customers\").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_sort.js" + }, + { + "language": "javascript", + "code": "[ { \n _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', \n address: 'Apple st 652'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a, \n name: 'Betty', address: 'Green Grass 1'}, { _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: \n 'Main Road 989'}, { _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: \n 'Mountain 21'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'}, { _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley 345'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', \n address: 'Sky st 331'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd 2'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way \n 98'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address: 'Yellow Garden 2'}, { _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway \n 1633'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8f, name: 'William', \n address: 'Central st 954'}]" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var mysort = { name: -1 }; dbo.collection(\"customers\").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); \n });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_sort_desc.js" + }, + { + "language": "javascript", + "code": "[ { \n _id: 58fdbf5c0ef8a50b4cdd9a8f, name: 'William', \n address: 'Central st 954'}, { _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway \n 1633'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address: 'Yellow Garden 2'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way \n 98'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd 2'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', \n address: 'Sky st 331'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'}, { _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley 345'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'}, { _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: \n 'Main Road 989'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a, \n name: 'Betty', address: 'Green Grass 1'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', \n address: 'Apple st 652'}]" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_delete.asp", + "content": "Node.js MongoDB Delete\n\n❮ Previous\nNext ❯\n\n\nDelete Document\nTo delete a record, or document as it is called in MongoDB, we use the\ndeleteOne() method.\nThe first parameter of the deleteOne() method \nis a query object defining which document to delete.\n\nNote: If the query finds more than one document, only the first \noccurrence is deleted.\n\n\nExample\nDelete the document with the address \"Mountain 21\":\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";\n MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var myquery = { address: 'Mountain 21' }; \n dbo.collection(\"customers\").deleteOne(myquery, function(err, obj) { \n if (err) throw err; console.log(\"1 \n document deleted\"); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_delete.js\" and run the file:\n\nRun \"demo_delete.js\"\n\nC:\\Users\\Your Name>node demo_delete.js\n\n\nWhich will give you this result:\n\n1 document deleted\n\n\n\n\n\n\n\nDelete Many\nTo delete more than one document, use the\ndeleteMany() method.\nThe first parameter of the deleteMany() method \nis a query object defining which documents to delete.\n\nExample\nDelete all documents were the address starts with the letter \"O\":\n\n var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";\n MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var myquery = { address: /^O/ }; \n dbo.collection(\"customers\").deleteMany(myquery, function(err, obj) { \n if (err) throw err; console.log(obj.result.n + \" \n document(s) deleted\"); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_delete_many.js\" and run the file:\n\nRun \"demo_delete_many.js\"\n\nC:\\Users\\Your Name>node demo_delete_many.js\n\n\nWhich will give you this result:\n\n2 document(s) deleted\n\n\nThe Result Object\nThe deleteMany() method returns an object which contains information about how \nthe execution affected the database.\nMost of the information is not important to understand, but one object inside \nthe object is called \"result\" which tells us if the execution went OK, and how \nmany documents were affected.\nThe result object looks like this:\n\n\n { n: 2, ok: 1 }\n\nYou can use this object to return the number of deleted documents:\n\nExample\nReturn the number of deleted documents:\n\n console.log(obj.result.n);\n\nWhich will produce this result:\n\n\n 2\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";\n MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var myquery = { address: 'Mountain 21' }; \n dbo.collection(\"customers\").deleteOne(myquery, function(err, obj) { \n if (err) throw err; console.log(\"1 \n document deleted\"); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_delete.js" + }, + { + "language": "javascript", + "code": "1 document deleted" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;\n var url = \"mongodb://localhost:27017/\";\n MongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\");\n var myquery = { address: /^O/ }; \n dbo.collection(\"customers\").deleteMany(myquery, function(err, obj) { \n if (err) throw err; console.log(obj.result.n + \" \n document(s) deleted\"); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_delete_many.js" + }, + { + "language": "javascript", + "code": "2 document(s) deleted" + }, + { + "language": "javascript", + "code": "{ n: 2, ok: 1 }" + }, + { + "language": "javascript", + "code": "console.log(obj.result.n);" + }, + { + "language": "javascript", + "code": "2" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_drop.asp", + "content": "Node.js MongoDB Drop\n\n❮ Previous\nNext ❯\n\n\nDrop Collection\nYou can delete a table, or collection as it is called in MongoDB, by using \nthe drop() method.\nThe drop() method takes a callback function \ncontaining the error object and the result parameter which returns true if the collection was dropped successfully, \notherwise it returns false.\n\nExample\nDelete the \"customers\" table:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").drop(function(err, delOK) { \n if (err) throw err; if (delOK) console.log(\"Collection \n deleted\"); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_drop.js\" and run the file:\n\nRun \"demo_drop.js\"\n\nC:\\Users\\Your Name>node demo_drop.js\n\n\nWhich will give you this result:\n\nCollection deleted\n\n\n\n\n\n\n\ndb.dropCollection\nYou can also use the dropCollection() method to delete a table (collection).\nThe dropCollection() method takes two parameters: the name of the collection \nand a callback function.\n\nExample\nDelete the \"customers\" collection, using dropCollection():\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.dropCollection(\"customers\", function(err, delOK) { \n if (err) throw err; if (delOK) console.log(\"Collection \n deleted\"); db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_dropcollection.js\" and run the file:\n\nRun \"demo_dropcollection.js\"\n\nC:\\Users\\Your Name>node demo_dropcollection.js\n\n\nWhich will give you this result:\n\nCollection deleted\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").drop(function(err, delOK) { \n if (err) throw err; if (delOK) console.log(\"Collection \n deleted\"); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_drop.js" + }, + { + "language": "javascript", + "code": "Collection deleted" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.dropCollection(\"customers\", function(err, delOK) { \n if (err) throw err; if (delOK) console.log(\"Collection \n deleted\"); db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_dropcollection.js" + }, + { + "language": "javascript", + "code": "Collection deleted" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_update.asp", + "content": "Node.js MongoDB Update\n\n❮ Previous\nNext ❯\n\n\nUpdate Document\nYou can update a record, or document as it is called in MongoDB, by using \nthe updateOne() method.\nThe first parameter of the updateOne() method \nis a query object defining which document to update.\n\nNote: If the query finds more than one record, only the first \noccurrence is updated.\n\nThe second parameter \nis an object defining the new values of the document.\n\nExample\nUpdate the document with the address \"Valley 345\" to name=\"Mickey\" and \naddress=\"Canyon 123\":\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://127.0.0.1:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myquery = { address: \"Valley 345\" }; var newvalues = { \n $set: {name: \n \"Mickey\", address: \"Canyon 123\" } }; dbo.collection(\"customers\").updateOne(myquery, \n newvalues, function(err, res) { if (err) throw err; \n console.log(\"1 document updated\"); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_update_one.js\" and run the file:\n\nRun \"demo_update_one.js\"\n\nC:\\Users\\Your Name>node demo_update_one.js\n\n\nWhich will give you this result:\n\n1 document updated\n\n\n\n\n\n\n\nUpdate Only Specific Fields\nWhen using the $set operator, only the \nspecified fields are updated:\n\nExample\nUpdate the address from \"Valley 345\" to \"Canyon 123\":\n\n ... var myquery = { address: \"Valley 345\" }; var newvalues \n = { $set: { address: \"Canyon 123\" } }; dbo.collection(\"customers\").updateOne(myquery, \n newvalues, function(err, res) {...\nRun example »\n\n\nUpdate Many Documents\nTo update all documents that meets the criteria of the query, use \nthe updateMany() method.\n\nExample\nUpdate all documents where the name starts with the letter \"S\":\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://127.0.0.1:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myquery = { address: /^S/ }; var newvalues = {$set: {name: \n \"Minnie\"} }; \n dbo.collection(\"customers\").updateMany(myquery, newvalues, function(err, \n res) { if (err) throw err; \n console.log(res.result.nModified + \" document(s) updated\"); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_update_many.js\" and run the file:\n\nRun \"demo_update_many.js\"\n\nC:\\Users\\Your Name>node demo_update_many.js\n\n\nWhich will give you this result:\n\n2 document(s) updated\n\n\nThe Result Object\nThe updateOne() and the\nupdateMany() methods return an object which contains information about how \nthe execution affected the database.\nMost of the information is not important to understand, but one object inside \nthe object is called \"result\" which tells us if the execution went OK, and how \nmany documents were affected.\nThe result object looks like this:\n\n\n { n: 1, nModified: 2, ok: 1 }\n\nYou can use this object to return the number of updated documents:\n\nExample\nReturn the number of updated documents:\n\n console.log(res.result.nModified);\n\nWhich will produce this result:\n\n\n 2\n\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://127.0.0.1:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myquery = { address: \"Valley 345\" }; var newvalues = { \n $set: {name: \n \"Mickey\", address: \"Canyon 123\" } }; dbo.collection(\"customers\").updateOne(myquery, \n newvalues, function(err, res) { if (err) throw err; \n console.log(\"1 document updated\"); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_update_one.js" + }, + { + "language": "javascript", + "code": "1 document updated" + }, + { + "language": "javascript", + "code": "... var myquery = { address: \"Valley 345\" }; var newvalues \n = { $set: { address: \"Canyon 123\" } }; dbo.collection(\"customers\").updateOne(myquery, \n newvalues, function(err, res) {..." + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://127.0.0.1:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n var myquery = { address: /^S/ }; var newvalues = {$set: {name: \n \"Minnie\"} }; \n dbo.collection(\"customers\").updateMany(myquery, newvalues, function(err, \n res) { if (err) throw err; \n console.log(res.result.nModified + \" document(s) updated\"); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_update_many.js" + }, + { + "language": "javascript", + "code": "2 document(s) updated" + }, + { + "language": "javascript", + "code": "{ n: 1, nModified: 2, ok: 1 }" + }, + { + "language": "javascript", + "code": "console.log(res.result.nModified);" + }, + { + "language": "javascript", + "code": "2" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_limit.asp", + "content": "Node.js MongoDB Limit\n\n❮ Previous\nNext ❯\n\n\nLimit the Result\nTo limit the result in MongoDB, we use the limit() \nmethod.\nThe limit() method takes one parameter, a number defining how many documents \nto return.\nConsider you have a \"customers\" collection:\n\ncustomers\n[ { _id: \n 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', \n address: 'Apple st 652'}, { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a , \n name: 'Betty', address: 'Green Grass 1'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', \n address: 'Sky st 331'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way \n 98'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden 2'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', \n address: 'Central st 954'}, { _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: \n 'Main Road 989'}, { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway \n 1633'}]\n\n\nExample\nLimit the result to only return 5 documents:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find().limit(5).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_limit.js\" and run the file:\n\nRun \"demo_mongodb_limit.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_limit.js\n\n\nWhich will give you this result:\n\ncustomers\n[ { _id: \n 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', \n address: 'Apple st 652'}, { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', \n address: 'Valley 345'}]\n\nAs you can see from the result above, only the 5 first documents were \nreturned.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "[ { _id: \n 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', \n address: 'Apple st 652'}, { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley 345'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd 2'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8a , \n name: 'Betty', address: 'Green Grass 1'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', \n address: 'Sky st 331'}, { _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way \n 98'}, { _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden 2'}, \n { _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', \n address: 'Central st 954'}, { _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: \n 'Main Road 989'}, { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway \n 1633'}]" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://localhost:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection(\"customers\").find().limit(5).toArray(function(err, result) { \n if (err) throw err; console.log(result); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_limit.js" + }, + { + "language": "javascript", + "code": "[ { _id: \n 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'}, { _id: \n 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet 4'}, { \n _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', \n address: 'Apple st 652'}, { _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: \n 'Mountain 21'}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', \n address: 'Valley 345'}]" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_mongodb_join.asp", + "content": "Node.js MongoDB Join\n\n❮ Previous\nNext ❯\n\n\nJoin Collections\nMongoDB is not a relational database, but you can perform a left outer join \nby using the $lookup stage.\nThe $lookup stage lets you specify which \ncollection you want to join with the current collection, and which \nfields that should match.\nConsider you have a \"orders\" collection and a \"products\" collection:\n\norders\n[ { _id: 1, product_id: \n 154, status: 1 }]\n\n\nproducts\n[ { _id: 154, name: \n 'Chocolate Heaven' }, { _id: 155, name: 'Tasty Lemons' }, { \n _id: 156, name: 'Vanilla Dreams' }]\n\n\nExample\nJoin the matching \"products\" document(s) to the \"orders\" collection:\n\n var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://127.0.0.1:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection('orders').aggregate([ { $lookup: \n { from: 'products', \n localField: 'product_id', \n foreignField: '_id', \n as: 'orderdetails' } \n } ]).toArray(function(err, \n res) { if (err) throw err; \n console.log(JSON.stringify(res)); \n db.close(); });});\nRun example »\n\nSave the code above in a file called \"demo_mongodb_join.js\" and run the file:\n\nRun \"demo_mongodb_join.js\"\n\nC:\\Users\\Your Name>node demo_mongodb_join.js\n\n\nWhich will give you this result:\n\n[ { \"_id\": 1, \"product_id\": \n 154, \"status\": 1, \"orderdetails\": [ { \"_id\": 154, \"name\": \n \"Chocolate Heaven\" } ] }]\n\nAs you can see from the result above, the matching document from the products \ncollection is included in the orders collection as an array.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "[ { _id: 1, product_id: \n 154, status: 1 }]" + }, + { + "language": "javascript", + "code": "[ { _id: 154, name: \n 'Chocolate Heaven' }, { _id: 155, name: 'Tasty Lemons' }, { \n _id: 156, name: 'Vanilla Dreams' }]" + }, + { + "language": "javascript", + "code": "var MongoClient = require('mongodb').MongoClient;var url = \"mongodb://127.0.0.1:27017/\";\nMongoClient.connect(url, function(err, db) { if (err) throw err; \n var dbo = db.db(\"mydb\"); \n dbo.collection('orders').aggregate([ { $lookup: \n { from: 'products', \n localField: 'product_id', \n foreignField: '_id', \n as: 'orderdetails' } \n } ]).toArray(function(err, \n res) { if (err) throw err; \n console.log(JSON.stringify(res)); \n db.close(); });});" + }, + { + "language": "javascript", + "code": "C:\\Users\\Your Name>node demo_mongodb_join.js" + }, + { + "language": "javascript", + "code": "[ { \"_id\": 1, \"product_id\": \n 154, \"status\": 1, \"orderdetails\": [ { \"_id\": 154, \"name\": \n \"Chocolate Heaven\" } ] }]" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi.asp", + "content": "Node.js and Raspberry Pi\n\n❮ Previous\nNext ❯\n\n\nRaspberry Pi is a small, multi-use computer.\nWith Node.js you can do amazing things with your Raspberry Pi.\n\nWhat is the Raspberry Pi?\nThe Raspberry Pi is a small, affordable, and amazingly capable, credit card \nsize computer.\nIt is developed by the Raspberry Pi Foundation, and it might be the most \nversatile tech ever created.\nCreator Eben Upton's goal was to create a low-cost device that would improve \nprogramming skills and hardware understanding.\nDue to the small size and price of the device, it has become the center of a \nwide range of projects by tinkerers, makers, and electronics enthusiasts.\n\nRaspberry Pi and Node.js\nThe Raspberry Pi has a row of GPIO (General Purpose input/output) pins, and \nthese can be used to interact in amazing ways with the real world. This tutorial \nwill focus on how to use these with Node.js.\n\nWhat Do I Need?\nFor this tutorial you need a Raspberry Pi. In our examples we use a Raspberry Pi 3, \nbut this tutorial should work for most versions.\nHardware needed:\n\nRaspberry Pi computer\nMicroSD memory card (We recommend a class 10 with 16 GB or higher)\nMicroSD to SD memory card adapter (usually included with the MicroSD card)\nMicro USB power supply to power the Raspberry Pi (2.5A or greater \n recommended)\nWiFi/Ethernet Cable connection for the Raspberry Pi (Not needed for \n Raspberry Pi 3 as it has built in WiFi)\nA working computer with internet and SD memory card reader (used to get the OS \n (Operating System) for the Raspberry Pi onto the memory card). In our tutorial \n we use a Windows computer for this, but you can use a Mac or Linux computer if \n you prefer\nHDMI monitor, USB keyboard (we need these only temporarily for the first \n boot of the Raspberry Pi)\n\nFor later chapters in this tutorial we will use special sensors or devices \nthat we connect to the Raspberry Pi. We will specify these as special \nrequirements in the relevant chapters.\nIf you already have a Raspberry Pi set up with Raspbian, internet and enabled \nSSH, you can skip to the step \"Install Node.js on Raspberry Pi\".\n\nWrite Raspbian OS Image to MicroSD Card\nBefore we can start using our Raspberry Pi for anything, we need to get a OS \ninstalled.\nRaspbian is a free operating system based on Debian Linux, and it is \noptimized Raspberry Pi.\nDownload the latest Raspbian image from https://www.raspberrypi.org/downloads/raspbian/ \nto your computer.\nWe use the \"LITE\" version in our tutorial, since we are setting the Raspberry \nPi up as a headless server (we will connect to it through SSH, without having a \nkeyboard/display connected to it). You can use whichever version you want, but \nthis tutorial is written with the \"LITE\" version as its focus.\nInsert the MicroSD memory card in your computer (via the SD adapter if \nneeded). \nOpen File Explorer to verify that it is operational.\nEtcher is a program for flashing images to memory cards. Download and \ninstall Etcher from: https://etcher.io/\nLaunch Etcher:\n\nClick \"Select image\" button and find the Raspbian zip file that \nyou downloaded.\nClick the \"Select drive\" button and specify the memory card as the target location.\nClick the \"Flash!\" button to write the image to the memory card.\nAfter Etcher is finished writing the image to the memory card, remove it from your computer.\n\nSet up Your Raspberry Pi\nTo get the Raspberry Pi ready to boot we need to:\n\nInsert the MicroSD memory card into the Raspberry Pi\nConnect the USB keyboard\nConnect the HDMI cable\nConnect the USB Wi-Fi adapter (or Ethernet cable). Skip this step if you \n are using a Raspberry Pi 3\nConnect the micro USB power supply\nThe Raspberry Pi should now be booting up\n\nWhen the Raspberry Pi is finished booting up, log in using username: pi and password: raspberry\n\nSet Up Network on the Raspberry Pi\nIf you will use a Ethernet cable to connect your Raspberry Pi to the \ninternet, you can skip this step.\nFor this section we will assume you have a Raspberry Pi 3, with built in \nWiFi.\nStart by scanning for wireless networks:\n\n pi@raspberrypi:~ $ \n sudo iwlist wlan0 scan\n\nThis will list all of the available WiFi networks. (It also confirms that \nyour WiFi is working)\nNow we need to open the wpa-supplicant file, to add the network you want to \nconnect to:\n\n pi@raspberrypi:~ $ sudo \n nano /etc/wpa_supplicant/wpa_supplicant.conf\nThis will open the file in the Nano editor. Add the following to the bottom \nof the file (change wifiName and wifiPassword with the actual network name and \npassword):\n\n network={ ssid=\"wifiName\" psk=\"wifiPassword\"} \nPress \"Ctrl+x\" to save the code. Confirm with \"y\", and confirm the name with \"Enter\".\nAnd reboot the Raspberry Pi:\n\n pi@raspberrypi:~ $ sudo reboot\nAfter reboot, log in again, and confirm that the WiFi is connected and working:\n\n pi@raspberrypi:~ $ ifconfig wlan0\nIf the WiFi is working propery, the information displayed should include an \nIP address, similar to this:\n\n inet addr:192.168.1.50\nWrite down that IP address, as we will use it to connect to the Raspberry Pi \nvia SSH.\n\n\n\n\n\n\nEnable SSH, Change Hostname and Password\nNow your Raspberry Pi is connected to the internet, it is time to enable SSH.\nSSH allows you up use the Raspberry Pi without having a monitor and keyboard \nconnected to it.\n(You will need a SSH client for this on your non-Raspberry Pi computer. We use \nPuTTY for windows)\nOpen the Raspberry Pi Software Configuration Tool:\n\n pi@raspberrypi:~ $ sudo raspi-config\nYou should see a menu like this:\n\nSelect option 5 Interfacing Options:\n\nSelect option P2 SSH, to activate SSH:\n\nConfirm with YES, to activate SSH:\n\nSSH is now enabled, and you should be in the main menu again.\nSelect 1 Change User Password, and follow the instructions to change the password. Choose a secure password, but something you will remember:\n\nAfter you have finished changing the password, you should be back in the main menu.\nSelect 2 Hostname, and follow the instructions to change the hostname:\n\nAfter you have finished changing the hostname, you should be back in the main menu.\nNow we will close the menu and save the changes:\n\nWhen selecting Finish, you will get the option to reboot. Select Yes to reboot the Raspberry Pi.\n\nYou can now unplug the monitor and keyboard from the Raspberry Pi, and we can log in using out SSH client.\nOpen PuTTY, type in the IP address for your Raspberry Pi, and click Open:\n\nLog in using the username pi and the new password you specified.\nYou should now see a command line like this: (we used w3demopi as our hostname)\n\n pi@w3demopi:~ $\n\nYou are now able to run your Raspberry Pi in \"Headless-mode\", meaning you do not need a monitor or keyboard. And if you have a WiFi connection, you do not need a ethernet cable either, just the power cable!\n\nInstall Node.js on Raspberry Pi\nWith the Raspberry Pi properly set up, login in via SSH, and update your Raspberry Pi system packages to their latest versions.\nUpdate your system package list:\n\n pi@w3demopi:~ $ sudo apt-get update\n\nUpgrade all your installed packages to their latest version:\n\n pi@w3demopi:~ $ sudo apt-get dist-upgrade\n\n\nDoing this regularly will keep your Raspberry Pi installation up to date.\n\nTo download and install newest version of Node.js, use the following command:\n\n pi@w3demopi:~ $ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -\nNow install it by running:\n\n pi@w3demopi:~ $ sudo apt-get install -y nodejs\nCheck that the installation was successful, and the version number of \nNode.js with:\n\n pi@w3demopi:~ $ node -v\n\nGet Started with Raspberry Pi and Node.js\nNow you have a Raspberry Pi with Node.js installed!\nIf you want to learn more about Node.js, follow our tutorial:\nhttps://www.w3schools.com/nodejs/\nIn the next chapter we will get to know the GPIO and how to use it with \nNode.js.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_gpio_intro.asp", + "content": "Node.js Raspberry Pi - GPIO Introduction\n\n❮ Previous\nNext ❯\n\n\nWhat is GPIO?\nGPIO stands for General Purpose Input Output.\nThe Raspberry Pi has two rows of GPIO pins, which are connections between the \nRaspberry Pi, and the real world.\nOutput pins are like switches that the Raspberry Pi can turn on or off (like \nturning on/off a LED light). But it can also send a signal to another device.\nInput pins are like switches that you can turn on or off from the outside \nworld (like a on/off light switch). But it can also be a data from a sensor, or \na signal from another device.\nThat means that you can interact with the real world, and control devices and \nelectronics using the Raspberry PI and its GPIO pins!\n\nTaking a Closer Look at the GPIO Pins\n\nThis is an illustration of the Raspberry Pi 3.\nThe GPIO pins are the small \nred squares in two rows on the right side of the Raspberry Pi, on the actual Raspberry Pi they are small metal pins.\nThe Raspberry Pi 3 has 26 GPIO pins, the rest of the pins are power, ground \nor \"other\".\nThe pin placements correspond with the table below.\n\n\nRaspberry Pi B+, 2, 3 & Zero\n\n\n3V3\n1\n2\n5V\n\n\nGPIO 2\n3\n4\n5V\n\n\nGPIO 3\n5\n6\nGND\n\n\nGPIO 4\n7\n8\nGPIO 14\n\n\nGND\n9\n10\nGPIO 15\n\n\nGPIO 17\n11\n12\nGPIO 18\n\n\nGPIO 27\n13\n14\nGND\n\n\nGPIO 22\n15\n16\nGPIO 23\n\n\n3V3\n17\n18\nGPIO 24\n\n\nGPIO 10\n19\n20\nGND\n\n\nGPIO 9\n21\n22\nGPIO 25\n\n\nGPIO 11\n23\n24\nGPIO 8\n\n\nGND\n25\n26\nGPIO 7\n\n\nDNC\n27\n28\nDNC\n\n\nGPIO 5\n29\n30\nGND\n\n\nGPIO 6\n31\n32\nGPIO 12\n\n\nGPIO 13\n33\n34\nGND\n\n\nGPIO 19\n35\n36\nGPIO 16\n\n\nGPIO 26\n37\n38\nGPIO 20\n\n\nGND\n39\n40\nGPIO 21\n\n\n\n\nLegend\n\nPhysical Pin Number\nPower +\nGround\nUART\nI2C\nSPI\nGPIO\nDo Not Connect\n\n\n\n\n\n\n\n\n\nTaking a Closer Look at the Breadboard\nA breadboard is used for prototyping electronics, it allows you to create \ncircuits without soldering. It is basically a plastic board, with a grid of \ntie-points (holes). Inside the board there are metal strips connecting the \ndifferent tie-points in specific ways.\nIn the illustration below we have highlighted some of the sections with different colors. This is to show you how the grid is connected.\n\nThe different sections of the breadboard:\n\nOn the left, and right, side there are 2 columns of tie-points. All the \n tie points in each of these columns are connected.\nThe Power Bus - The columns highlighted with red. There are usually used \n to connect power to the Breadboard. Since the entire column is connected, \n you can connect power to any of the tie-points in the column.\nThe Ground Bus - The columns highlighted with blue. There are usually \n used to connect Ground to the Breadboard. Since the entire column is \n connected, you can connect ground to any of the tie-points in the column.\nRows of connected Tie-Points - The rows highlighted with green. The \n tie-points of each of these rows are connected, but not the entire row! The \n left side tie-points are connected (A-B-C-D-E), and the right side \n tie-points are connected (F-G-H-I-J).\nIn the center of the Breadboard there is a Trench, this separates the \n left and right rows. The width of the trench is designed so that many \n Integrated Circuits fit across it.\n\n\nInstall the onoff Module\nTo interface with the GPIO on the Raspberry Pi using Node.js, we will use a \nModule called \"onoff\".\nInstall the onoff module using npm:\n\n pi@w3demopi:~ $ npm install onoff\n\nNow onoff should be installed and we can interact with the GPIO of the Raspberry Pi.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_blinking_led.asp", + "content": "Node.js Raspberry Pi GPIO - Blinking LED\n\n❮ Previous\nNext ❯\n\n\nUsing the GPIO for Output\nIn this chapter we will use a Raspberry Pi and its GPIO to \nmake a LED blink.\nWe use Node.js with the onoff module to control the GPIO.\nTo get a LED light to turn on, we use a GPIO pin as \"Output\", and create a \nscript to turn it on and off (blinking).\n\n\nWhat do we need?\nIn this chapter we will create a simple example where \nwe control a LED light.\nFor this you need:\n\nA Raspberry Pi with Raspian, internet, SSH, with Node.js installed\nThe \n onoff module for Node.js\n1 x Breadboard\n1 x \n 68 Ohm resistor\n1 x \n Through Hole LED\n2 x \n Female to male jumper wires\n\nClick the links in the list above for descriptions of the different \ncomponents.\n\nNote: The resistor you need can be different from what we use depending on the type of LED you use. Most small LEDs only need a small resistor, around 200-500 ohms. It is generally not critical what exact value you use, but the smaller the value of the resistor, the brighter the LED will\nshine.\n\n\nBuilding the Circuit\nNow it is time to build the circuit on our Breadboard.\nIf you are new to electronics, we recommend you turn off the power for \nthe Raspberry Pi. And use an anti-static mat or a grounding strap to avoid \ndamaging it.\nShut down the Raspberry Pi properly with the command:\n\n pi@w3demopi:~ $ sudo shutdown -h now\n\nAfter the LEDs stop blinking on the Raspberry Pi, then pull out the power \nplug from the Raspberry Pi (or turn off the power strip it is connected to).\nJust pulling the plug without shutting down properly may cause corruption of the memory card.\n\nLook at the above illustration of the circuit.\n\nOn the Raspberry Pi, connect the female leg of the first jumper wire to \n Ground. You can use any GND pin. In this example we used Physical Pin 9 (GND, \n row 5, left column)\nOn the Breadboard, connect the male leg of the first jumper wire to \n the Ground Bus column on the right. That entire \n column of your breadboard is connected, so it doesn't matter which row. In \n this example we have attached it to row 1\nOn the Raspberry Pi, connect the female leg of the second jumper cable \n to a GPIO pin. In this example we used Physical Pin \n 7 (GPIO 4, row 4, left \n column)\nOn the Breadboard, connect the male leg of the second jumper wire to the \n Tie-Point row of your choice. In this example we connected it to row 5, \n column A\nOn the Breadboard, connect one leg of the resistor to the Ground Bus \n column on the right side. That entire column of your breadboard is \n connected, so it doesn't matter which row. In this example we have attached \n it to row 5\nOn the Breadboard, connect the other leg of the resistor to the right \n side Tie-Point row of your choice. In this example we have used row 5, \n column J\nOn the Breadboard, connect the cathode leg (the shortest leg) of the \n LED to the same Tie-Point row that you connected the resistor from GND \n to. In this example we used row 5, column F\nOn the Breadboard, connect the anode leg (the longest leg) of the \n LED to the same Tie-Point row that you connected the jumper from \n the GPIO pin to. In this example we used row \n 5, column E\n\nYour circuit should now be complete, and your connections should look \n pretty similar to the illustration above.\nNow it is time to boot up the Raspberry Pi, and write the Node.js script to \n interact with it.\n\n\n\n\n\n\n\nRaspberry Pi and Node.js Blinking LED Script\nNow that we have everything set up, we can write a script to turn the LED on and off.\nStart by making a directory where we can keep our Node.js scripts:\n\n pi@w3demopi:~ $ mkdir nodetest\n\nGo to our new directory:\n\n pi@w3demopi:~ $ cd nodetest\n\nNow we will create a new file called \"blink.js\" using the Nano Editor:\n\n pi@w3demopi:~ $ nano blink.js\n\nThe file is now open and can be edited with the built in Nano Editor.\nWrite, or paste the following code:\n\nblink.js\n\n var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIOvar LED = new Gpio(4, 'out'); \n //use GPIO pin 4, and specify that it is outputvar \n blinkInterval = setInterval(blinkLED, 250); //run the blinkLED function every \n 250msfunction blinkLED() { //function to start blinking if (LED.readSync() === \n 0) { //check the pin state, if the state is 0 (or off) LED.writeSync(1); \n //set pin state to 1 (turn LED on) } else { LED.writeSync(0); \n //set pin state to 0 (turn LED off) }}function endBlink() \n { //function to stop blinking clearInterval(blinkInterval); // Stop blink intervals \n LED.writeSync(0); // Turn LED off LED.unexport(); // Unexport GPIO \n to free resources}setTimeout(endBlink, 5000); //stop blinking \n after 5 seconds\n\nPress \"Ctrl+x\" to save the code. Confirm with \"y\", and confirm the name with \"Enter\".\nRun the code:\n\n pi@w3demopi:~ $ node blink.js\n\nNow the LED should blink for 5 seconds (10 times) before turning off again!\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIOvar LED = new Gpio(4, 'out'); \n //use GPIO pin 4, and specify that it is outputvar \n blinkInterval = setInterval(blinkLED, 250); //run the blinkLED function every \n 250msfunction blinkLED() { //function to start blinking if (LED.readSync() === \n 0) { //check the pin state, if the state is 0 (or off) LED.writeSync(1); \n //set pin state to 1 (turn LED on) } else { LED.writeSync(0); \n //set pin state to 0 (turn LED off) }}function endBlink() \n { //function to stop blinking clearInterval(blinkInterval); // Stop blink intervals \n LED.writeSync(0); // Turn LED off LED.unexport(); // Unexport GPIO \n to free resources}setTimeout(endBlink, 5000); //stop blinking \n after 5 seconds" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_led_pushbutton.asp", + "content": "Node.js Raspberry Pi GPIO - LED and Pushbutton\n\n❮ Previous\nNext ❯\n\n\nUsing both Input and Output\nIn the previous chapter we learned how to use a Raspberry Pi and its GPIO to \nmake a LED blink.\nFor that we used a GPIO pin as \"Output\".\nIn this chapter we will use another GPIO pin as \"Input\".\nInstead of blinking for 5 seconds, we want the LED to light up when you push \na button connected to the breadboard.\n\nWhat do we need?\nIn this chapter we will create a simple example where \nwe control a LED light with a Push Button.\nFor this you need:\n\nA Raspberry Pi with Raspian, internet, SSH, with Node.js installed\nThe \n onoff module for Node.js\n1 x Breadboard\n1 x 68 Ohm resistor\n1 x 1k Ohm resistor\n1 x Through Hole LED\n1 x Push Button\n4 x Female to male jumper wires\n1 x Male to Male jumper wires\n\nClick the links in the list above for descriptions of the different \ncomponents.\n\nNote: The resistor you need can be different from what we use depending on the type of LED you use. Most small LEDs only need a small resistor, around 200-500 ohms. It is generally not critical what exact value you use, but the smaller the value of the resistor, the brighter the LED will\nshine.\n\nIn this chapter we will build on the circuit we built in last chapter, so you \nwill recognize some of the parts in the list above.\n\nBuilding the Circuit\nNow it is time to build the circuit on our Breadboard. We will use the circuit we created in the last chapter as a starting point.\nIf you are new to electronics, we recommend you turn off the power for \nthe Raspberry Pi. And use an anti-static mat or a grounding strap to avoid \ndamaging it.\nShut down the Raspberry Pi properly with the command:\n\n pi@w3demopi:~ $ sudo shutdown -h now\n\nAfter the LEDs stop blinking on the Raspberry Pi, then pull out the power \nplug from the Raspberry Pi (or turn of the power strip it is connected to).\nJust pulling the plug without shutting down properly may cause corruption of the memory card.\n\nLook at the above illustration of the circuit.\n\nStarting with the circuit we created in the last chapter:\n On the Raspberry Pi, connect the female leg of a jumper wire to a \n 5V \n power pin. In our example we used Physical Pin 2 (5V, \n row 1, right column)\nOn the Breadboard, connect the male leg of the jumper wire connected to \n the 5V power, to the \n Power Bus on the right side. That entire column \n of your breadboard is connected, so it doesn't matter which row. In our \n example we attached it to row 1\nOn the Breadboard, connect the push button so that it fits across the \n Trench. In our example it connects to rows 13 and 15, columns E and F\nOn the Breadboard, connect one leg of the 1k ohm resistor to the Ground Bus \n column on the right side, and the other leg to the right side Tie-Point row \n where it connects to one of the right side legs of the push button. In our example we attached \n one side to Tie-Point row 13, column J, and the other side to the closest Ground Bus hole\nOn the Breadboard, connect a male-to-male jumper wire from the right \n Power Bus, to the right Tie-Point row that \n connects to the other leg of the \n push button. In our example we attached \n one side to Tie-Point row 15, column J, and the other side to the closest Power Bus hole\nOn the Raspberry Pi, connect the female leg of a jumper wire to a \n GPIO pin. In our example we used Physical Pin \n 11 (GPIO 17, row 6, left \n column)\nOn the Breadboard, connect the male leg of the jumper wire to left \n Tie-Point row the Push Button leg that is directly across the \n Ground connection leg. In our example we \n attached it to row 13, column A\n\nYour circuit should now be complete, and your connections should look \n pretty similar to the illustration above.\nNow it is time to boot up the Raspberry Pi, and write the Node.js script to \n interact with it.\n\n\n\n\n\n\n\nRaspberry Pi and Node.js LED and Button Script\nGo to the \"nodetest\" directory, and create a new file called \"buttonled.js\":\n\n pi@w3demopi:~ $ nano buttonled.js\n\nThe file is now open and can be edited with the built in Nano Editor.\nWrite, or paste the following:\n\nbuttonled.js\n\n var\n Gpio = require('onoff').Gpio; //include onoff to interact with the GPIOvar \n LED = new Gpio(4, 'out'); //use GPIO pin 4 as outputvar pushButton = new \n Gpio(17, 'in', 'both'); //use GPIO pin 17 as input, and 'both' button presses, \n and releases should be handledpushButton.watch(function (err, value) { \n //Watch for hardware interrupts on pushButton GPIO, specify callback function \n if (err) { //if an error console.error('There was an \n error', err); //output error message to console return; } \n LED.writeSync(value); //turn LED on or off depending on the button state (0 or \n 1)});\n function unexportOnClose() { //function to run when exiting program \n LED.writeSync(0); // Turn LED off LED.unexport(); // Unexport LED \n GPIO to free resources pushButton.unexport(); // Unexport Button \n GPIO to free resources};process.on('SIGINT', unexportOnClose); //function to \n run when user closes using ctrl+c\n\nPress \"Ctrl+x\" to save the code. Confirm with \"y\", and confirm the name with \"Enter\".\nRun the code:\n\n pi@w3demopi:~ $ node buttonled.js\n\nNow the LED should turn on when you press the button, and turn off when you \nrelease it.\nEnd the program with Ctrl+c.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var\n Gpio = require('onoff').Gpio; //include onoff to interact with the GPIOvar \n LED = new Gpio(4, 'out'); //use GPIO pin 4 as outputvar pushButton = new \n Gpio(17, 'in', 'both'); //use GPIO pin 17 as input, and 'both' button presses, \n and releases should be handledpushButton.watch(function (err, value) { \n //Watch for hardware interrupts on pushButton GPIO, specify callback function \n if (err) { //if an error console.error('There was an \n error', err); //output error message to console return; } \n LED.writeSync(value); //turn LED on or off depending on the button state (0 or \n 1)});\n function unexportOnClose() { //function to run when exiting program \n LED.writeSync(0); // Turn LED off LED.unexport(); // Unexport LED \n GPIO to free resources pushButton.unexport(); // Unexport Button \n GPIO to free resources};process.on('SIGINT', unexportOnClose); //function to \n run when user closes using ctrl+c" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_flowing_leds.asp", + "content": "Node.js Raspberry Pi GPIO - Flowing LEDs\n\n❮ Previous\nNext ❯\n\n\nUsing Array With Output to Create Flowing LEDs\nIn this chapter we will use several GPIO pins to create a \"flowing\" effect by \nturning them on and off in sequence.\n\n\nWhat do we need?\nFor this you need:\n\nA Raspberry Pi with Raspian, internet, SSH, with Node.js installed\nThe \n onoff module for Node.js\n1 x Breadboard\n8 x 220 Ohm resistor\n8 x Through Hole LED\n9 x Female to male jumper wires\n\n\nNote: The resistor you need can be different from what we use depending on the type of LEDs you use. Most small LEDs only need a small resistor, around 200-500 ohms. It is generally not critical what exact value you use, but the smaller the value of the resistor, the brighter the LED will\nshine.\n\nClick the links in the list above for descriptions of the different \ncomponents.\n\nBuilding the Circuit\nNow it is time to build the circuit on our Breadboard.\nIf you are new to electronics, we recommend you turn off the power for \nthe Raspberry Pi. And use an anti-static mat or a grounding strap to avoid \ndamaging it.\nShut down the Raspberry Pi properly with the command:\n\n pi@w3demopi:~ $ sudo shutdown -h now\n\nAfter the LEDs stop blinking on the Raspberry Pi, then pull out the power \nplug from the Raspberry Pi (or turn of the power strip it is connected to).\nJust pulling the plug without shutting down properly may cause corruption of the memory card.\n\nLook at the above illustration of the circuit.\n\nOn the Raspberry Pi, connect the female leg of a jumper wire to a GND pin. In our example we used Physical Pin 6 (GND, \n row 3, right column)\nOn the Breadboard, connect the male leg of the jumper wire connected to \n the GND power, to the Ground Bus on the right side. That entire column \n of your breadboard is connected, so it doesn't matter which row. In our example we attached it to row 1\nFor each LED: Connect the LED so that it connects to 2 Tie-Point rows. In our example \n we connected:\nLED1 to rows 5 (cathode) & 6 (anode) column J\nLED2 to rows 8 (cathode) & 9 (anode) column J\nLED3 to rows 11 (cathode) & 12 (anode) column J\nLED4 to rows 14 (cathode) & 15 (anode) column J\nLED5 to rows 17 (cathode) & 18 (anode) column J\nLED6 to rows 20 (cathode) & 21 (anode) column J\nLED7 to rows 23 (cathode) & 24 (anode) column J\nLED8 to rows 26 (cathode) & 27 (anode) column J\n\n\nFor each LED: Connect one of the legs of a 220 ohm resistor from the the Ground Bus \n column on the right side, and the other leg to the right side Tie-Point row \n where it connects to the cathode leg of the LED. In our example we \n connected:\nLED1 to row 5 column I\nLED2 to row 8 column I\nLED3 to row 11 column I\nLED4 to row 14 column I\nLED5 to row 17 column I\nLED6 to row 20 column I\nLED7 to row 23 column I\nLED8 to row 26 column I\n\n\nFor each LED: Connect the female leg of a jumper wire to a\n GPIO pin on the Raspberry Pi, and the male leg \n of the jumper wire to the right side Tie-Point row \n where it connects to the anode leg of the LED. In our example we connected:\nLED1 from Physical Pin \n 7 (GPIO 4, row 4, left \n column) to Tie-point row 6 column F\nLED2 from Physical Pin \n 11 (GPIO 17, row 6, left \n column) to Tie-point row 9 column F\nLED3 from Physical Pin \n 13 (GPIO 27, row 7, left \n column) to Tie-point row 12 column F\nLED4 from Physical Pin \n 15 (GPIO 22, row 8, left \n column) to Tie-point row 15 column F\nLED5 from Physical Pin \n 12 (GPIO 18, row 6, right \n column) to Tie-point row 18 column F\nLED6 from Physical Pin \n 16 (GPIO 23, row 8, right column) to \n Tie-point row 21 column F\nLED7 from Physical Pin \n 18 (GPIO 24, row 9, right column) to \n Tie-point row 24 column F\nLED8 from Physical Pin \n 22 (GPIO 25, row 11, right column) to \n Tie-point row 27 column F\n\n\n\nYour circuit should now be complete, and your connections should look \n pretty similar to the illustration above.\nNow it is time to boot up the Raspberry Pi, and write the Node.js script to \n interact with it.\n\n\n\n\n\n\n\nRaspberry Pi and Node.js Flowing LEDs Script\nGo to the \"nodetest\" directory, and create a new file called \"flowingleds.js\":\n\n pi@w3demopi:~ $ nano \n flowingleds.js\n\nThe file is now open and can be edited with the built in Nano Editor.\nWrite, or paste the following:\n\nflowingleds.js\n\n var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO\n var LED04 = new Gpio(4, 'out'), //use declare variables for all the GPIO \n output pins LED17 = new Gpio(17, 'out'), LED27 = new Gpio(27, \n 'out'), LED22 = new Gpio(22, 'out'), LED18 = new Gpio(18, \n 'out'), LED23 = new Gpio(23, 'out'), LED24 = new Gpio(24, \n 'out'), LED25 = new Gpio(25, 'out');//Put all the LED \n variables in an arrayvar leds = [LED04, \n LED17, LED27, LED22, LED18, LED23, LED24, LED25];var indexCount = 0; //a \n counterdir = \"up\"; //variable for flowing directionvar \n flowInterval = setInterval(flowingLeds, 100); //run the flowingLeds function \n every 100msfunction flowingLeds() { //function for flowing Leds \n leds.forEach(function(currentValue) { //for each item in array \n currentValue.writeSync(0); //turn off LED }); if (indexCount \n == 0) dir = \"up\"; //set flow direction to \"up\" if the count reaches zero \n if (indexCount >= leds.length) dir = \"down\"; //set flow direction to \"down\" if \n the count reaches 7 if (dir == \"down\") indexCount--; //count \n downwards if direction is down leds[indexCount].writeSync(1); \n //turn on LED that where array index matches count if (dir == \n \"up\") indexCount++ //count upwards if direction is up};function unexportOnClose() { \n //function to run when exiting program clearInterval(flowInterval); \n //stop flow interwal leds.forEach(function(currentValue) { //for \n each LED currentValue.writeSync(0); //turn off LED \n currentValue.unexport(); //unexport GPIO });};process.on('SIGINT', unexportOnClose); //function to \n run when user closes using ctrl+cc\n\nPress \"Ctrl+x\" to save the code. Confirm with \"y\", and confirm the name with \"Enter\".\nRun the code:\n\n pi@w3demopi:~ $ node flowingleds.js\n\nNow the LEDs should turn on and off in sequence, creating a flowing effect.\nEnd the program with Ctrl+c.\n\n\n❮ Previous\nNext ❯\n\n\n\n\n\n\n\n\n\n\n\n\n★\n+1\n\n\n\n \n\n\n\nTrack your progress - it's free!\n\n\n \n\n\n\n\n\n\n\n Log in\n \n\n Sign Up", + "code_examples": [ + { + "language": "javascript", + "code": "var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO\n var LED04 = new Gpio(4, 'out'), //use declare variables for all the GPIO \n output pins LED17 = new Gpio(17, 'out'), LED27 = new Gpio(27, \n 'out'), LED22 = new Gpio(22, 'out'), LED18 = new Gpio(18, \n 'out'), LED23 = new Gpio(23, 'out'), LED24 = new Gpio(24, \n 'out'), LED25 = new Gpio(25, 'out');//Put all the LED \n variables in an arrayvar leds = [LED04, \n LED17, LED27, LED22, LED18, LED23, LED24, LED25];var indexCount = 0; //a \n counterdir = \"up\"; //variable for flowing directionvar \n flowInterval = setInterval(flowingLeds, 100); //run the flowingLeds function \n every 100msfunction flowingLeds() { //function for flowing Leds \n leds.forEach(function(currentValue) { //for each item in array \n currentValue.writeSync(0); //turn off LED }); if (indexCount \n == 0) dir = \"up\"; //set flow direction to \"up\" if the count reaches zero \n if (indexCount >= leds.length) dir = \"down\"; //set flow direction to \"down\" if \n the count reaches 7 if (dir == \"down\") indexCount--; //count \n downwards if direction is down leds[indexCount].writeSync(1); \n //turn on LED that where array index matches count if (dir == \n \"up\") indexCount++ //count upwards if direction is up};function unexportOnClose() { \n //function to run when exiting program clearInterval(flowInterval); \n //stop flow interwal leds.forEach(function(currentValue) { //for \n each LED currentValue.writeSync(0); //turn off LED \n currentValue.unexport(); //unexport GPIO });};process.on('SIGINT', unexportOnClose); //function to \n run when user closes using ctrl+cc" + } + ], + "next_link": "https://profile.w3schools.com/log-in" + }, + { + "title": "No Title Found", + "url": "https://www.w3schools.com/nodejs/nodejs_raspberrypi_webserver_websocket.asp", + "content": "Node.js and Raspberry Pi - Webserver with WebSocket\n\n❮ Previous\nNext ❯\n\n\nWhat is WebSocket?\nWebSocket enables bidirectional communication in real time over the web.\nWebSocket can be run together with a normal HTTP server. You can click a button in a web browser, and enable a GPIO on your Raspberry Pi which turns on a light in your house. All in real time, and with communication going both ways!\nIn this chapter, we will set up a web server with WebSocket. Then create a browser UI to interact with our earlier example of turning a LED on and off with a button.\n\n\nWhat Do I Need?\nFor this tutorial you need a Raspberry Pi. In our examples we use a a Raspberry Pi 3, \nbut this tutorial should work for most versions.\nFor this you need:\n\nA Raspberry Pi with Raspian, internet, SSH, with Node.js installed\nThe \n onoff module for Node.js\nThe \n socket.io module for Node.js\n1 x Breadboard\n1 x \n 68 Ohm resistor\n1 x \n 1k Ohm resistor\n1 x \n Through Hole LED\n1 x \n Push Button\n4 x \n Female to male jumper wires\n1 x \n Male to Male jumper wires\n\nClick the links in the list above for descriptions of the different \ncomponents.\n\nNote: The resistor you need can be different from what we use depending on the type of LED you use. Most small LEDs only need a small resistor, around 200-500 ohms. It is generally not critical what exact value you use, but the smaller the value of the resistor, the brighter the LED will\nshine.\n\nCompared to our earlier example, the only new thing we need is to set up a \nweb server, and install the socket.io module.\n\nWebserver for Raspberry Pi and Node.js\nFollowing the earlier chapters in this Node.js tutorial, lets set up a web \nserver that can serve HTML files.\nIn our \"nodetest\" directory create a new directory we can use for static html files:\n\n pi@w3demopi:~/nodetest $ \n mkdir public\nNow lets set up a webserver. Create a Node.js file that opens the requested \nfile and returns the content to the client. If anything goes wrong, throw a 404 \nerror.\n\n pi@w3demopi:~/nodetest $ \n nano webserver.js\n\nwebserver.js:\n\n var http = require('http').createServer(handler); //require http server, and \n create server with function handler()var fs = require('fs'); //require filesystem modulehttp.listen(8080); //listen to port 8080\n function handler (req, res) { //create server fs.readFile(__dirname + '/public/index.html', function(err, data) { //read \n file index.html in public folder if (err) \n { res.writeHead(404, \n {'Content-Type': 'text/html'}); //display 404 on error \n return res.end(\"404 Not Found\"); } res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML res.write(data); //write data from index.html \n return res.end(); });}\n\nGo to the folder \"public\":\n\n pi@w3demopi:~/nodetest $ \n cd public\n\nAnd create a HTML file, index.html:\n\n pi@w3demopi:~/nodetest/public $ \n nano index.html\n\nindex.html:\n\nOr pick a color: \n
Or pick a color: \n