Home > front end >  MongoDB not showing the Data sent or created from the Model
MongoDB not showing the Data sent or created from the Model

Time:11-11

I have been working on CRUD app with express and mongoDB using mongoose, for some reason all the data created on model schema is not being reflected on MongoDB. I am not sure what I am getting wrong but I am asking someone to help me with why the data created on model is not showing in the mongoDB as if I go postman and excute get method for http:/localhost:5001/jobs it gives me the output shown below. Also below are all my files to get your guidance.

sample data posted on POSTMAN using post router:

{
     "username": "test",
     "job_title": "DevOps",
     "job_comp_image": "https://pixabay.com/images/id-1869401/",
     "job_comp_name": "Training Academy",
     "job_description":"Web Developer",
     "job_location": "City",
     "job_field": "IT",
     "job_closing_date": "2021-11-07T04:11:08.924Z",
     "job_date_created" : "2021-11-07T04:11:08.924Z"
}

POSTMAN GET output after a sample job was posted:

        "_id": "618bb690fbef67502a29854b",
        "username": "test",
        "job_closing_date": "2021-11-10T12:09:52.427Z",
        "job_date_created": "2021-11-10T12:09:52.427Z",
        "createdAt": "2021-11-10T12:09:52.428Z",
        "updatedAt": "2021-11-10T12:09:52.428Z",
        "__v": 0

jobs.model.js


const mongoose = require('mongoose');

const Schema = mongoose.Schema;


const jobsiteSchema = new Schema ({

    username: String,
    job_title: String ,
    job_comp_image: String,
    job_comp_name: String,
    job_description: String,
    job_location:  String,
    job_field: String ,
    job_closing_date: { type: Date, default: Date.now},
    job_date_created: { type: Date, default: Date.now },
}, {
    timestamps: true,
});  

const Job =  mongoose.model("Job", jobsiteSchema) ;

module.exports = Job;

jobs.js

const router = require('express').Router();
let Job = require('../models/jobs.model');

router.route('/').get((req, res) => {
  Job.find()
    .then(jobs => res.json(jobs))
    .catch(err => res.status(400).json('Error: '   err));
});

router.route('/add').post((req, res) => {

  const username = req.body.username;
  const jobTitle = req.body.job_title;
  const JobCompImage = req.body.job_comp_image;
  const JobCompName = req.body.job_comp_name;
  const JobDescription = req.body.job_description;
  const JobLocation = req.body.job_location;
  const JobField = req.body.job_field;
  const JobClosingDate = req.body.job_closing_date ;
  const JobPostingDate = Date.parse(req.body.job_date_created) ;
  

  console.log(username)
  console.log(jobTitle)
  console.log(JobCompImage)
  console.log(JobCompName)
  console.log(JobDescription)
  console.log(JobLocation)
  console.log(JobField)
  console.log(JobClosingDate)
  console.log(JobPostingDate)

  // Create new Job using the fields above
  const newJob = new Job({
    username:username,
    jobTitle : jobTitle,
    JobCompImage : JobCompImage,
    JobCompName: JobCompName,
    JobDescription: JobDescription,
    JobLocation: JobLocation,
    JobField : JobField,
    JobClosingDate : JobClosingDate,
    JobPostingDate : JobPostingDate
  });

  //Save the new Job
  newJob.save()
    .then(() => res.json('Job added!'))
    .catch(err => res.status(400).json('Error: '   err));
});

router.route('/:id').get((req, res) => {
  Job.findById(req.params.id)
    .then(job => res.json(job))
    .catch(err => res.status(400).json('Error: '   err));
});

router.route('/:id').delete((req, res) => {
    Job.findByIdAndDelete(req.params.id)
    .then(() => res.json('Job deleted.'))
    .catch(err => res.status(400).json('Error: '   err));
});

router.route('/update/:id').post((req, res) => {
    Job.findById(req.params.id)
    .then(job => {
    

     // username = req.body.username;
      job.jobTitle = req.body.job_title;
      job.JobCompImage = req.body.job_comp_image;
      job.JobCompName = req.body.job_comp_name
      job.JobDescription = req.body.job_description;
      job.JobLocation = req.body.job_location;
      job.JobField = req.body.job_field;
      job.JobClosingDate = req.body.job_closing_date ;

      job.save()
        .then(() => res.json('Job updated!!!'))
        .catch(err => res.status(400).json('Error: '   err));
    })
    .catch(err => res.status(400).json('Error: '   err));
});

module.exports = router;

server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require("path");

require('dotenv').config();

const app = express();

const jobsRouter = require('./routes/jobs');
const usersRouter = require('./routes/users');

app.use(cors());
app.use(express.json());

// ... other app.use middleware 
app.use(express.static(path.join(__dirname, "backend", "build")));

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, 
                  { useNewUrlParser: true, 
                    //useCreateIndex: true,
                    useUnifiedTopology: true 
                 }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})



app.use('/jobs', jobsRouter);
app.use('/users', usersRouter);

const port = process.env.PORT || 5001;

// Right before your app.listen(), add this:
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "backend", "build", "index.html"));
});

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
})

CodePudding user response:

It's due to wrong variable names: Your schema has variable names defined in the underscore case and you are passing data in MongoDB in camelCase.

As username matches you get that value stored. All the timestamp have default values so you get those values too.

const jobsiteSchema = new Schema ({

    username: String,
    job_title: String ,
    job_comp_image: String,
    job_comp_name: String,
    job_description: String,
    job_location:  String,
    job_field: String ,
    job_closing_date: { type: Date, default: Date.now},
    job_date_created: { type: Date, default: Date.now },
}, {
    timestamps: true,
})

Change your routing hander to following:

router.route('/add').post((req, res) => {
    const newJob = new Job(req.body);

    //Save the new Job
    newJob.save()
        .then(() => res.json('Job added!'))
        .catch(err => res.status(400).json('Error: '   err));
    });

It's ideal to add validation of the req body before storing it to DB.

  • Related