Binding DropDownList With MongoDB In Node.js

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.


  • 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');

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) {
        // 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="">
    <meta charset="utf-8" />
    <h1>Bind DropDownList</h1>
    <label>Name: </label>
        <% for (const i in dropdownVals) { %>
        <option value="<%= dropdownVals[i].id %>"> <%= dropdownVals[i].name %> </option>
        <% } %>



Also, check File Uploads With Node.js

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories