3
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....

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

14 Comments

using above code i am getting the same TypeError. Is there any change that I have to do? My error: TypeError: Book.getBook is not a function
check this out add callback in app.get and send by callback.
If it is saying TypeError: Book.getBook is not function than the Book file is not imported properly . Add the code of Book model let me check
below is my book.js file: var mongoose = require('mongoose'); //Book Schma as per the db fields // create instance of Schema var bookSchma = mongoose.Schema({ title:{ type:String, required:true }, genre:{ type:String, required:true }, create_date:{ type:Date, default:Date.now } }); // create model if not exists. var Book = module.exports = mongoose.model('Book',bookSchma); //Get Book module.exports.getBooks =function(callback,limit){ Book.find(callback).limit(limit); }
@kalpita check out now. Your function name was wrong and pass limit with function , i have updated code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.