3

This is my server.js.

var express          = require('express'),
    app              = express(),
    bodyParser       = require('body-parser'),
    mongoose         = require('mongoose'),
    CohortController =require('./CohortController');

var MongoURL='mongodb://username:password@ds037395.mongolab.com:37395/abc';

mongoose.connect(MongoURL,function (error) {
    if (error) 
        console.error(error);
    else
        console.log('mongo connected');
});


app.use(bodyParser());

app.get('/api/cohorts',CohortController.list);
app.post('/api/cohorts',CohortController.create);

app.listen(3000,function(){ 
  console.log('Listening...');
})

And my CohortController.js

 var mongoose=require('mongoose');

 var Cohort=mongoose.model('Cohorts',new Schema({
 id:Number,
 name:String
 }));
module.exports.create=function(req,res){
var cohort=new Cohort(req.body);
cohort.save(function(err,result){
res.json(result);
 });
}

module.exports.list=
function(req,res){
  Cohort.find({},function(err,results){
   res.json(results);
 });
}

When I run the node server and use the URL

localhost:3000/api/cohorts

I am getting null JSON i.e [] but when I connect it with the local mongodb instance I get the correct JSON.

Venkat.R
  • 7,420
  • 5
  • 42
  • 63
Shubham Pendharkar
  • 310
  • 1
  • 4
  • 17

2 Answers2

0

Try createConnection:

//Connect
var db = mongoose.createConnection(MongoURL);
db.on('error', console.error.bind(console, 'connection error:'));

//Once connected do actions
db.once('open', function callback () {
    console.log('Connected to DB: '+MongoURL); 
});

And add a category sshcema or any schema you want:

    var category = new Schema({
        name : String,
        quantity : Number
    });

    db.categories = db.model('categories', category)
AugustoL
  • 354
  • 1
  • 7
0

Add collection in schema.

var schema = new Schema({
  id:Number,
  name:String
}, { collection: 'actor' });

// or

schema.set('collection', 'actor');

// or

var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)
Venkat.R
  • 7,420
  • 5
  • 42
  • 63