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);