traveller traveller - 6 months ago 12
Node.js Question

Cannot read from database using mongoose

This is my

GET
request

var Catalog = mongoose.model('Catalog');
router.get('/catalog', function(req, res, next) {
Catalog.find(function(err, items){
if(err){
return next(err);
}
console.log(items);
res.json(items);
});
});


The model

var mongoose = require('mongoose');

var CatalogSchema = new mongoose.Schema({
title: String,
cost: String,
description: String
});

mongoose.model('Catalog', CatalogSchema);


The
console.log
gives me a
[]
but there is a collection named
Catalog
with the parameters filled.

Answer

If you have an existing collection, created outside of Mongoose, that you wish to query you need to configure your model to use that collection.

Otherwise, Mongoose will use a utility function to create a collection name by pluralizing and lowercasing the model name (which in your case would become catalogs).

To use Catalog as a collection, use the collection option:

var CatalogSchema = new mongoose.Schema({
  title: String,
  cost: String,
  description: String
}, { collection : 'Catalog' });