In this tutorial we will allow users to enter a first name and a last name that will save to the MongoDB database.
I have used JetBrains WebStorm IDE for this tutorial.
Create a project in Webstorm to get started.
.
First step is to create a file that will contain the code for our Node.js server. So create a file and call it as app.js and include the below code.
In order for express , body-parser and mongoose to work you should install them to the package,json file as dependencies.
First, go to the directory of the project and run these commands in the command prompt.
1. npm init - The command prompt will ask you some questions and it will create the package.json file.
2.Then run these commands.
npm install express --save
npm install mongoose --save
npm install body-parser --save
After installing them you can open the package.json file and see whether those frameworks have been installed properly.
Create a html file and call it as index.html and paste the below code.
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB</title>
</head>
<body>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
</html>
After doing so save the code and go to the project directory open the command prompt and run node app.js to start our server.
Make sure your mongod is running.
Open up a browser and navigate to the url
http://localhost:3000
Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database.