Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error in json format in mongodb

var express=require('express');
var app=express();
var bodyParser=require('body-parser');
var mongoose=require('mongoose');
var createError = require('http-errors')


 app.use(bodyParser.json());


 Genre=require('./model/genre')
Book=require('./model/book')

//connect to Mongoose
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/bookstore', { useMongoClient: true});
var db=mongoose.connection;


 /*  "/api/books"
 *    GET: finds all books
 *    POST: creates a new book
  */
 app.get('/api/books',function(req,res){
 Book.getBook(function(err,book){
 if(err){

     throw err; //Want this error in json format
 }
  //JSON response will show all books in JSON format
 res.json(book);
    });
  });




     //Connection to the mongodb localhost
  app.listen(27017);
   console.log('Running on port 27017');

  error is:
    TypeError: Book.getBook is not a function

Please tell me how to throw error in json format as am new to mongodb..... I am using visual studio for the changes With that mongodb+node.js+express Want error should display in the json format....

like image 719
kalpita Avatar asked Mar 22 '26 02:03

kalpita


1 Answers

OK here is the way to throw error in json.

  app.get('/api/books',function(req,res,callback){
    Book.getBooks(function(err,book){
     if(err){
         res.status(404).send({ error: 'error in mongo of kalpita!' });

          }else{
          //JSON response will show all books in JSON format
            res.json(book);
           }
        },10);
      });

and also add

Book.find({},callback).limit(limit);

in model.

like image 140
Himanshu sharma Avatar answered Mar 23 '26 18:03

Himanshu sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!