0

I follow actually a training in nodejs, express and mongo.

I developed a rest webservice but when I try to access it, I have the current exception :

TypeError: Object # has no method 'find'

I don't understand what's happen exactly because my code seems correct and the same that in the tutorial.

Schema Definition

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

var bookModel = new Schema({
   title:{
       type:String
   },
    author:{type:String},
    genre:{type:String},
    read:{type:Boolean,default:false}

});

module.export= mongoose.model('Book',bookModel);

Definition of my service

var express = require('express'),
mongoose = require('mongoose');


var db = mongoose.connect('mongodb://localhost/bookAPI');

var Book = require('./models/bookModel');

var app = express();

var port = process.env.PORT || 3000;

var bookRouter = express.Router();

bookRouter.route('/books')
    .get(function(req,res){

    Book.find(function(err,books){
        if(err)
            console.log(err);
        else
            res.json(books);
    });

});

app.use('/api', bookRouter);

app.get('/',function(req,res){

    res.send('welcome to my api 2000');
})

app.listen(port, function(){
    console.log('Running on PORT: ' +port);

});

1 Answer 1

1

try this:

var Book= mongoose.model('Book',bookModel);

export module like this:

module.exports = {
    Book: Book
};

And import with following code:

var Book = require('./models/bookModel').Book;

after that write find query

Book.find({},function(err,books){
        if(err)
            console.log(err);
        else
            res.json(books);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks chirag, your solution works. Could you tell me why my import and export doesn't work correctly.

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.