0

Im trying to do a crud operation using mongoosejs,mongodb and nodejs. while im trying to make a post request im getting an error ("Unexpected token d in JSON at position 6")and couldn't quite figure out why im getting it. btw the retrieve part (get request) is working properly.im new to node and mongodb, heres my code

node app

 var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Book = require('./Book.model');

var db = 'mongodb://localhost/Book';

mongoose.connect(db);

var port = 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended:true
}));

app.get('/',function(req,res){
      res.send('Hello :)');
});

app.get('/books',function (req,res) {
  Book.find({}).exec(function (err,books) {
      if(err){
         res.send('Erorr '+err);
      }else {
         res.json(books);
      }
  });
});

app.get('/books/:id',function (req,res) {
  Book.findOne({
    _id:req.params.id
  }).exec(function (err,books) {
      if(err){
         res.send('Erorr '+err);
      }else {
         res.json(books);
      }
  });
});

app.post('/books',function (req,res) {
  var newBook = new Book();
  newBook.title=req.body.title;
  newBook.author=req.body.author;
  newBook.catrgory=req.body.category;
  newBook.save(function (err,books) {
    if (err) {
      res.send('error saving book '+err);
    }else {
      res.json(books);
    }
  });
});

app.listen(port,function () {
  console.log('app listening on port '+port);
});

Model,schema

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

var BookSchema = new Schema({
  title:String,
  author:String,
  catrgory:String
});

module.exports = mongoose.model('Book',BookSchema);
TRomesh
  • 4,323
  • 8
  • 44
  • 74
  • It will be nice to see stack trace [ http://stackoverflow.com/a/33593443/4989460 ]. – stdob-- May 20 '16 at 14:55
  • Can you show how and what data are you posting. It seems the bodyParser is trying to parse the body but the body is not properly formatted json. – Molda May 20 '16 at 15:06
  • Molda Opps i forgot to mention im using Postman to make post request – TRomesh May 20 '16 at 17:45

1 Answers1

2
app.post('/books',function (req, res) {
 Book.create(req.body)
   .then(function (createdBook) {
       //On success return a created object
       return res.json(createdBook);
    })
   .catch(function (err) {
      //On error return error
      return res.json(err);
    });
  });
});

Edit

Use method create to save object in db. Can you show us object wich you want to save?

IARKI
  • 197
  • 1
  • 6