Home > Enterprise >  (MEAN STACK) backend is saving objectId and __v : 0 in mongodb when i submit a form
(MEAN STACK) backend is saving objectId and __v : 0 in mongodb when i submit a form

Time:11-29

i'm working on a small CRUD application using MEAN STACK :

  • i have a form that should allow me to save a book's info in mongodb
  • when i submit, i find that i have ObjectID and __v : 0 saved in the database instead of the book's details ! here's my code :

backend :

booksRoute.route('/post').post((req,res,next)=>{
    var x = {
        name   : req.params.name,
        genre  : req.params.genre,   
        author : req.params.author,
        rating : req.params.rating,
        price  : req.params.price
    }
    console.log(x) ; 
    BookModel(x).save((err,x)=>{
        if (err){console.log(err);}
        else res.send(x) ;
    }) ;
})

mongoose model

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

let books = new Schema({
    name:{
        type:String
    },
    genre:{
        type:String
    },
    author:{
        type:String
    },
    rating:{
        type:Number
    },
    price:{
        type:Number
    }
},{
    collection: 'booklist' 
}) 

module.exports = mongoose.model('books',books) ; 

frontend

<ul>
    <form #f="ngForm" (ngSubmit)="onSubmit(f)">  
    <li>
    <label>book's name *</label>
    <input name="name" type="text" ngModel>
    </li>
    <li>
    <label>book's genre *</label>
    <input name="genre" type="text" ngModel>
    </li>
    <li>
    <label>book's author *</label>
    <input name="author" type="text" ngModel>
    </li>
    <li>
    <label>rating *</label>
    <input name="rating" type="number" [max]="10" min="0" ngModel>
    </li>
    <li>
    <label>price *</label>
    <input name="price" type="number" ngModel>
    <input  type="submit"/> 
    </li>  
</form>
</ul>

function that triggers the backend to save document

 onSubmit(f){
    //console.log(f.value) ;
    this.apiService.postBook(f.value).subscribe( res => {console.log('the back response:',res)}) ; 
  }

service

//post book
  postBook(data){
    console.log(data) ;
    return this.http.post(this.backendUrl '/post',data) ;
  }

CodePudding user response:

I think your problem is you are trying to take the values from req.params instead of req.body

  • Related