document saves no data after creating on valid data

Viewed 25

Below i have given a code for a test REST API.

// Imports
var express=require("express")
, mongoose=require("mongoose")
, bodyParser= require('body-parser')
, bodyParser = require("body-parser");
const { Int32 } = require("bson");


// Constants
const app = express()
const PORT=4002

// Our Schema
var data={
    value: Number
}

// Create a model
const dataModel=mongoose.model('dataCollection',mongoose.Schema(data))

// Making connection with database
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/testdb', {
    useNewUrlParser:true,
    useUnifiedTopology:true
})

// Create the controller to save data
function postData(req,res){
    console.log(req.body)
    let newData = new dataModel(req.body)
    newData.save((err,resp)=>{
        if(err) console.log(err)
        else res.json(resp)
    })
}

// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));


// express set root page
app.get('/',(req,res)=> res.send("ROOT PAGE"));

// Set Route for our post request
app.route('/app')
.get((req,res)=>res.send("Nothing here"))
.post(postData);

// start listening on server
app.listen(PORT,()=>console.log(`Your application is running on Port: ${PORT}`));

Below is the test of POST request test of this code: enter image description here

Below is the output produced by Node js:

node ./test.js

Your application is running on Port: 4002
{ userName: 'Adnan', UserID: '1', password: '123' }

The object below Port number in this output is produced by console.log(req.body) in postData but the response returned as seen in the screenshot above is an empty object which is stored in the collection instead of actual data.

1 Answers

You are not assigning any values to your newData object and your schema is different from the type of data that you are trying to store. Change your code like this:

       var data={
        //value: Number
        username: String,
        userId: String,
        password: String
       }

      // Create a model
      const dataModel=mongoose.model('dataCollection',mongoose.Schema(data))

      // Making connection with database
      mongoose.Promise= global.Promise;
      mongoose.connect('mongodb://localhost/testdb', {
        useNewUrlParser:true,
        useUnifiedTopology:true
      })

     // Create the controller to save data
    function postData(req,res){
     console.log(req.body)
     let newData = new dataModel();
     newData.username=req.body.userName;
     newData.userId=req.body.UserId;
     newData.password=req.body.password;
     newData.save((err,resp)=>{
       if(err) console.log(err)
       else res.json(resp)
     })
   }
Related