In node.js/expressjs how do i fetch the data from mongodb?

I will write the code in expressjs (i.e framework of nodejs).

Image result for express and mongoose
Before writing the the code make sure you have installed - 
  1. nodejs- https://nodejs.org/en/download/
  2. mongodb-https://www.mongodb.com/download-center/community
  3. Visual studio or any other code writting software - https://code.visualstudio.com/download
  • Open cmd in visual studio code by pressing ( ctrl + ` )  then type in cmd -
    npm init

  • Then install the dependencies by trying the command-
    npm install express mongoose
  • Then make two file named as server.js and User.js


1- server.js
  1. const express = require('express');
  2. const mongoose = require('mongoose');
  3. const User = require('./User.js'); // write User.js file path
  4.  
  5. const app = express();
  6.  
  7. mongoose.connect('mongodb://localhost/dbname', { useNewUrlParser: true})
  8. .then( console.log('connected to mongoose') )
  9. .catch( err => { console.log(err) } )
  10.  
  11. app.get('/', (req,res) => {
  12. User.find()
  13. .then(users => {
  14. res.json(users);
  15. })
  16. })
  17.  
  18. app.listen(3000);
2- User.js
  1. const mongoose = require('mongoose');
  2. const Schema = mongoose.Schema;
  3.  
  4. const UserSchema = new Schema({
  5. name: {
  6. type:string,
  7. required:true
  8. },
  9. email: {
  10. type:string,
  11. required:true
  12. },
  13. password: {
  14. type:string,
  15. required:true
  16. }
  17. })
  18.  
  19. module.exports = User = mongoose.model ('user', UserSchema);

  • After writing this code, type in cmd -
    node server.js
  • Then go to the browser and type localhost:3000 in url.

You will fetch the data of users from your database which you have made.
Initially your database will be empty so go to C:\Program Files\MongoDB\Server\4.0\bin
where you have installed mongodb and open mongo.exe file.
  1. After running the above code database with name dbname will be automatically made with collection name as users.
  2. So simply write the command in mongo.exe as-  use dbname    to enter the database.
  3. And finally write the command to insert items as -
    db.users.insert({name: 'John', email:'john@gmail.com', password:'john'})

Now reload the page of browser and you will see the user details in JSON format.
Enjoy :)

You can also visit -
Simple code for storing images coming from the frontend to Node.js using Mongoose?
I hope this will help.
Fell free to ask any doubt :)

Post a Comment

0 Comments