In this article, we will learn how to bind the Drop-Down List from the MongoDB database in Node.js.
A Drop-Down List is a graphical control element, that allows the user to choose one value from a list. When a Drop-Down List is activated, it displays a list of values, from which the user may select one. When inactive, it displays a single value.
Prerequisites:
- Basic knowledge of Node.js and MongoDB
- Code editor like Visual Studio 2019
If you’re new to Node.js? You must have to follow the link given below to set up a new Node.js App in Visual Studio.
How To Create Node.js App In Visual Studio
Bind a DropDownList in Node.js project
Here, we will use the existing student_info collection of the StudentDB database.
Firstly, we have to install a package to connect MongoDB Server.
Install the mongoose package with the NPM:
Right-click on the npm from Solution Explorer -> Install New npm Packages…
Search and install the mongoose package.
Now, right-click the project name in the Solution Explorer and select Add -> New Folder (Database).
Now, right-click the folder name (Database) in the Solution Explorer and select Add -> New File… (dbConnection.js).
Open the dbConnection.js file and add the code in it.
var mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/StudentDB'); var studentInfoSchema = mongoose.Schema({ name: String, age: Number }); mongoose.model("StudentInfo", studentInfoSchema, "student_info"); exports.use = function (modelName) { return mongoose.model(modelName); };
Open the index.js file from the routes folder and add the code to it.
'use strict'; var express = require('express'); var router = express.Router(); var db = require('../Database/dbConnection'); /* GET home page. */ router.get('/', function (req, res) { db.use("StudentInfo").find(function (err, response) { if (err) { console.log(err) } // Pass the DB result to the template res.render('index', { dropdownVals: response }) }); }); module.exports = router;
Open the index.html file from the views folder and add the code in it.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <h1>Bind DropDownList</h1> <label>Name: </label> <select> <% for (const i in dropdownVals) { %> <option value="<%= dropdownVals[i].id %>"> <%= dropdownVals[i].name %> </option> <% } %> </select> </body> </html>
Output:
Also, check File Uploads With Node.js