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

1 Like

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

      <html>  
<body>  
    <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">
    </form>
</body>  
</html> 

app.js

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;
mongoose.connect("mongodb://localhost:27017/Node");


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

is that all you need?

Hi,

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):

DATABASE=mongodb://localhost:27017/test

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

require('dotenv').config();
const mongoose = require('mongoose');
require('./models/User');

mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;
mongoose.connection
  .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(express.static('public'));
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) => {
  User.find()
    .then((users) => {
      res.json(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">
<head>
  <meta charset="UTF-8">
  <title>Ajax demo</title>
</head>
<body>
  <h1>Users</h1>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $.ajax({
      url: '/users',
      type: 'GET'
    })
    .done(function(users) {
      console.table(users);
    })
    .fail(function(e) {
      console.log(e);
    });
  </script>
</body>
</html>

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.

4 Likes

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.

console.time("dbLookup");
// fetch data
console.timeEnd("dbLookup");

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.

console.time("dbLookup");
// fetch data
console.timeEnd("dbLookup");

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.

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