Karthikeyan sundaramoorthi Karthikeyan sundaramoorthi - 2 months ago 13
Node.js Question

TypeError: .find(...) is not a function nodejs mongoose

I am working on samples in nodejs. I am struck with TypeError: Cars.find(...) is not a function
at D:\Karthikeyan\rest-server\routes\carsRouter.js:19:15 when i try to access http://localhost:3000/cars. thanks
App.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/myTest';
mongoose.connect(url);

var db = mongoose.connection;
db.on('error',console.error.bind(console,'Connection error'));

db.once('open',function(){
console.log("connected to db server");
});

var routes = require('./routes/index');
var users = require('./routes/users');
var carsRouter = require('./routes/carsRouter');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/cars',carsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;


routes/carsRouter.js

var express = require('express');
var bodyParser = require('body-parser'); /*Parses the data seerved from client*/
var mongoose = require('mongoose');
var Cars = require('../models/cars');
var carsRouter = express.Router(); /*with the help we have defined in global with router*/
carsRouter.use(bodyParser.json());

carsRouter.route('/')
.get(function(req,res,next){
Cars.find({})(function (err,cars) {
assert.equal(err,null);
res.json(cars);
});
})
.post(function(req,res,next){
Cars.create(req.body,function(err,cars){
if(err) throw err;
console.log('cars inserted');
var id = cars._id;
res.writeHead(200,{'content-type':'text/plain'});
res.end('the car you inserted is '+id);
});
})
.delete(function(req,res,next){
Cars.remove({},function(err,res){
if(err) throw err;
res.json(res);
});
});

carsRouter.route('/:carId')
.get(function(req,res,next){
Cars.findById(req.params.id,function(err,cars){
if(err) throw err;
res.json(cars);
});
})
.put(function(req,res,next){
Cars.findByIdAndUpdate(req.params.id,{
$set:req.body
},
{
new:true
},function(err,cars){
if(err) throw err;
res.json(cars);
});
})
.delete(function(req,res,next){
Cars.remove(req.params.id,function(err,res){
if(err) throw err;
res.json(res);
});
});

carsRouter.route('/:carId/comments')
.get(function(req,res,next){
Cars.findById(req.params.id,function(err,cars){
if(err) throw err;
res.json(cars.comments);
});
})
.post(function(req,res,next){
Cars.findById(req.params.id,function(err,cars){
if(err) throw err;
cars.comments.push(req.body);
cars.save(function (err,cars) {
if(err) throw err;
console.log('updated');
res.json(cars);
});
res.json(cars.comments);
});
})
.delete(function(req,res,next){
Cars.findById(req.params.id,function(err,cars){
if(err) throw err;
for (var i = (cars.comments.length - 1); i >= 0; i--){
cars.comments.id(cars.comments[i]._id).remove();
}
cars.save(function (err,cars) {
if(err) throw err;
console.log('updated');
res.json(cars);
});
});
Cars.remove(req.params.id,function(err,res){
res.writeHead(200,{'content-type':'text/plain'});
res.end('comments deleted');
});
});
module.exports = carsRouter;


models/cars.js

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

var commentsSchema = new Schema({
rating:{
type:Number,
min:1,
max:5,
required:true
},
comment:{
type:String,
required:true
},
price:{
type:String,
required:true
}
},
{
timestamps:true
});

var carsSchema = new Schema({
name:{
type: String,
required:true,
unique:true
},
description:{
type:String,
required:true
},
comments:[commentsSchema]

},
{timestamps:true});

var cars = mongoose.model('cars',carsSchema);

module.exports = cars;

Answer

You have used find query in wrong way the callback must be within find function

  carsRouter.route('/')
    .get(function(req, res, next) {
        Cars.find({}, function(err, cars) {
            assert.equal(err, null);
            res.json(cars);
        });
    });
Comments