0

I have created few collections on cloud mongodb on the same DB. Only some collections are returning values and others are not (just blank []) using nodeJS. No error msg or exceptions. I tested on mongodb shell and it shows data in all the collections.

I used this example to create my project. You can get full code from here. http://programmerblog.net/nodejs-mongodb-rest-api/

Here is my code in app, router, model, controller js files:

app.js

...
var  mongodburi = "mongodb+srv://myID:myPassword@cluster0-qabk1.mongodb.net/onlinestore";
.....
var routes = require('./restapi/routes/productRoutes');

productRoutes.js

...
 var product = require('../controllers/productController');
app.route('/products')
    .get(product.products)
----

productModel.js

    'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Schema = new Schema({
  product_name: { type: String, Required:  'Product name cannot be left blank.' },
  price:    { type: String,     Required:  'Product price cannot be left blank.'},
  category: { type: String ,    Required:  'Product category cannot be left blank'}
});
module.exports = mongoose.model('products', Schema);

productController.js

'use strict';

var mongoose = require('mongoose'),
    Product = mongoose.model('products');

exports.products = function(req, res) {
  Product.find({}, function(err, product) {
    if (err)
      res.send(err);
    res.json(product);
  });
};

Collection 1: products - I am getting the values Collection 2: techinfo - I am not getting the values Collection 3: tests - I am getting the values

I have created all these collections in the same way. I am just changing the collection name in code at 2 places: 1st. productModel.js at line module.exports = mongoose.model('techinfo', Schema); 2nd: productController.js at line Product = mongoose.model('techinfo');

why it works for products and tests and not for techinfo collection? (I even tried creating more collections but it's inconsistent).

Aatish
  • 1
  • 1

1 Answers1

0

Can't believe this framework does this. When you dont' pass the collection name, by default it adds 's' at the end of model name you are passing. That's why I was able to get the data from products and tests collections but not from techinfo.

This is what I was doing initially. That's why it was adding additional 's' by default.

module.exports = mongoose.model('techinfo', techInfoSchema);

If you want to call a particular collection, pass it like this:

module.exports = mongoose.model('techinfo', techInfoSchema, 'techinfo')

More info at: Why does mongoose always add an s to the end of my collection name

Aatish
  • 1
  • 1