Mo Hassan Mo Hassan - 16 days ago 7
Node.js Question

cannot get Nodejs express mongoose working

When I issue localhost:8000/api/customers I am getting empty array even though I inserted data in mongodb. I tested the route localhost:8000/api/customers without connecting to mongodb and it displays a static text.However, when connecting to Mongodb it returns empty array. here is the code

var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection err'));
db.once('open', function callback(){console.log('connected to db')});
var Customer = require('./Customers/models/customerModel');
var app = express(),
port = process.env.PORT || 3000,
customerRouter = express.Router();

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
customerRouter.route('/Customers')
.post(function(req, res){
var customer = new Customer(req.body);
console.log(customer);
res.send(customer);
})
.get(function(req,res){
Customer.find(function(err,customers){
if(err)
res.status(500).send(err);
else {
res.json(customers);
console.log(customers);
}
});
});
app.use('/api', customerRouter);
app.get('/', function (req, res) {
res.send('Welcome to my API')
});
app.listen(port, function () {
console.log('Running on port ' + port);
});


and the customerModel.js

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

var customerModel = new Schema({
name: {type: String},
contact: {type: String},
date_register: {type: String},
main_tel: {type: String},
tel_1: {type: String},
tel_2: {type: String},
tel_3: {type: String},
address: {type: String},
email: {type: String}
});

module.exports = mongoose.model('Customer', customerModel);


I am using gulp task runner on port 8000

Answer

You are not using Customer.find properly. Check out the docs:

http://mongoosejs.com/docs/api.html#model_Model.find

There are supposed to be two arguments for find(). The first argument is the criteria for the find method (the "WHERE" condition if you will), the second argument is the callback. Update your code from this:

Customer.find(function(err,customers){ ...

to this:

Customer.find({}, function(err,customers){ ...

Passing an empty object means "give me everything". If you later wanted to find all customers with the first name "John", you would do something like this:

Customer.find({firstName: "John"}, function(err,customers){ ...