1

I'm using mongoose to connect mongoDB. Its a nodeJS application. Right now I'm concerned to get the data and display it in my application. However, it doesn't show any error, neither it displays any data. Here's my server file

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

const employeeRoute = require('./routes/employee.route');
mongoose.Promise = global.Promise;

mongoose.connect(config.DB, { useNewUrlParser: true })
    .then(() => { console.log('Database is connected') },
        err => { console.log('Can not connect to the database' + err) }
    );

const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/Employees', employeeRoute);
let port = process.env.PORT || 4000;

const server = app.listen(port, function () {
    console.log('Listening on port ' + port);
})

and here's my route file

const express = require('express');
const employeeRoute = express.Router();

let Employees = require('../models/Employee');

employeeRoute.route('/').get(function (req, res) {
    let employees = [];
    Employees.find({}, function (err, results) {
        if (err) {
            console.log(err);
        }
        else {
            employees = results;
            console.log(employees)
            res.json(employees);
        }
    })
})
module.exports = employeeRoute

and lastly my employee.js file

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Employee = new Schema({
    first_name: { type: String },
    last_name: { type: String },
    title: { type: String },
    email: { type: String },
    gender: { type: String },
    location: { type: String },
    phone: { type: Number }
},
    { collation: 'Employees' });
module.exports = mongoose.model('Employees', Employee)


Application runs fine without any error. Before posting it to the forum, I've double checked the db and collection names. any suggestions

3
  • is useNewUrlPars the correct option term? Shouldn't it be useNewUrlParser ? - just reading through the rest now. Commented Aug 23, 2019 at 9:28
  • does you console shows 'Database is connected' if yes, make sure you are connected to correct database. can you go and check if you have records in your Employee document. Sometimes the problem is very tiny but we think its huge. Commented Aug 23, 2019 at 10:29
  • yes it shows Database is connected and I also ensured that I have data in my collection Commented Aug 23, 2019 at 10:30

2 Answers 2

1

It looks like you might just need to refactor your route a little bit in order to ensure you get the results you want. For example, take a look at my following example:

const express = require('express');
const employeeRoute = express.Router();

let Employees = require('../models/Employee');

employeeRoute.route('/').get(function (req, res) {
  // Extract data from the request object here in order to search for employees. For example:
  const name = req.body.name;
  const surname = req.body.surname;

  let employees = [];

  // Now perform a find on your specific data:
  Employees.find({ first_name: name, last_name: surname }, function(err, results) {
    if (err) console.log(err);
    else employees = results; 

    console.log(JSON.stringify(employees));
    res.json(employees);
  });

  // Or you can perform a find on all employees
  Employees.find({}, function(err, results) {
    if (err) console.log(err);
    else employees = results; 

    console.log(JSON.stringify(employees));
    res.json(employees);
  });

})
module.exports = employeeRoute

As I mentioned in my comment too, your connection may need to be changed to use the correct term: useNewUrlParser

EDIT

I also noticed that in your Employee Schema, you put collation instead of collection - see below:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Employee = new Schema({
    first_name: { type: String },
    last_name: { type: String },
    title: { type: String },
    email: { type: String },
    gender: { type: String },
    location: { type: String },
    phone: { type: Number }
}, { collection: 'employees' });

module.exports = mongoose.model('Employees', Employee)

Try that, does it make any difference?

Sign up to request clarification or add additional context in comments.

Comments

0

You are doing it wrong buddy.Here's a sample way of inserting data using mongoose.

employeeRoute.route('/').get(function (req, res) {
        Employees.create({your_data}) // ex: {email:req.body.email}
              .then((employee)=>{
                   console.log(employee)
                   res.json(employee);
               }).catch((err)=> {
                   console.log(err);
                   res.status(400).send({message: "your message"})
               })

})
module.exports = employeeRoute

10 Comments

I want to read the data from database not insert buddy, thanks. Looking at your code now
let emp = new Employees(res); console.log(res); this line made me confused!!
I've updated the code in question, please look at that now
first of all make sure that your app can conncet to mongo. mongoose.connect(config.DB, { useNewUrlParser: true }) .then( () => { console.log('Database is connected') }) .catch( err => { console.log('Can not connect to the database' + err) })
and make sure, actually you have data in employees collection
|