Select * from mongodb using node js


Hi All,

Does anyone know how to select * from mongodb database and display it on html page once a button has been clicked

I am unable to do so currently any help would be much appreciated


Are you using something like Mongoose to create your schema? If so, what does it look like?


//Makes the model for nameSchema 
var User = mongoose.model("Users", nameSchema);

var nameSchema = new mongoose.Schema({
  name: String,
  email: String,
  qebsite: String

I have noticed you can also use console.time() to do the same that php offer such as microtime to check how long it takes to submit or fetch data from the database and shows time in milliseconds do you know how to do this also ?


You would attach an event listener to the button, that when clicked would fire off an Ajax request to your server. On the server you would perform the database query and pass the result back to the script running on your web page to display.

What part are you having trouble with? And what does your server setup look like? Are you running Express?


Yes I am running express my html page looks like this

    <form method="get" action="/Select">
 Email:     <input type="text" name="email">
 Name:     <input type="text" name="name">
 Website:     <input type="text" name="qebsite">
      <input type="submit" value="Add Name">


var express = require('express');
var path = require('path');
var app = express();
var port = process.env.PORTH || 8080;
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/View')); // all HTML files will be found in the view folder
app.use(express.static(__dirname + '/Scripts')); // all scripts such as CSS and JS files will be using the scripts folder

// connecting to mongodb you need to require the mongoose module and then connect using the localhost connection string
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;

//Makes the model for nameSchema 
var User = mongoose.model("Users", nameSchema);
var nameSchema = new mongoose.Schema({
  name: String,
  email: String,
  qebsite: String

is that all you need?



So let's do this from scratch and change the structure slightly. This will help you organize your app as it grows.

Create the following folder structure:

├── app.js
├── models
│   └── User.js
├── package.json
├── public
│   └── index.html
├── routes
│   └── index.js
└── start.js
└── .env

Install the dependencies:

npm i -S dotenv express mongoose

Create a new Mongo database called test. Add a collection called users and ensure there is at least one document in it with a name and and email field.

Now in .env add your DB connection details (assuming a local install of Mongo):


In start.js let's set up Mongo and add the code to kick off the server:

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;
  .on('connected', () => {
    console.log(`Mongoose connection open on ${process.env.DATABASE}`);
  .on('error', (err) => {
    console.log(`Connection error: ${err.message}`);

const app = require('./app');

const server = app.listen(3000, () => {
  console.log(`Express is running on port ${server.address().port}`);

Now in app.js require express, configure it to serve anything in the public directory as a static asset and include a routes file:

const express = require('express');
const routes = require('./routes/index');

const app = express();

app.use('/', routes);

module.exports = app;

In routes/index.js we'll handle the DB lookup:

const express = require('express');
const mongoose = require('mongoose');

const router = express.Router();
const User = mongoose.model('User');

router.get('/users', (req, res) => {
    .then((users) => {
    .catch(() => { res.send('Sorry! Something went wrong.'); });

module.exports = router;

Now define a User model in models/User.js:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
  email: {
    type: String,

module.exports = mongoose.model('User', userSchema);

Finally, wire up public/index.html to send the Ajax request. I'm using jQuery for convenience:

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>Ajax demo</title>

  <script src=""></script>
      url: '/users',
      type: 'GET'
    .done(function(users) {
    .fail(function(e) {

This will fetch all of the users in the DB and log them to the console when the page loads. It should be fairly easy to have that happen on button click, though.

Now start the app with node start.js and hit http:localhost/3000 to see the result.

Hopefully that gives you something to work with.


Thank you so much I will let you know how I get on, have you ever usefd Console.time to log the execution time? I would like to display in miliseconds to seconds how long it had taken to get the data from mongodb

Once again thanks for the advice


I don't have any experience of it, but it should be possible. Just wrap the DB call in calls to console.time using a common identifier.

// fetch data


I have followed all of the above but noticed it does not log the database info in the log? any reason for this it just shows the title of the html page Users

any reason for this to happen


It should log the contents of the users table to the browser console. Is this not what you are seeing?


oh brilliant I did not know it was doing this, I thought it was going to the cmd shell thanks so much


No worries. I had assumed that you would be wanting to insert a list of users (for example) into the page, hence returning the data to the client for further processing.


// fetch data

Are you saying add this in the Ajax script on the HTML page?


Nope, to the Node script running on the server. That will then log it to the Node console.


brilliant it works thank you for the help.

closed #16

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.