Mo Hassan Mo Hassan - 9 months ago 64
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');

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();

.post(function(req, res){
var customer = new Customer(req.body);
else {
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 Source

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

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){ ...