Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model.find() returns empty in mongoose [duplicate]

i am working upon mongoose to list all the data from a collection in a db in mongodb:

from the requests:

http://localhost:3000/listdoc?model=Organization 

i am doing the following code :

exports.listDoc = function(req, res) {     var Model = mongoose.model(req.query.model); //This is defined and returns my desired model name         Model.find().populate('name').exec(function(err, models) {             if (err) {                 res.render('error', {                     status: 500                 });             } else {                 res.jsonp(models);             }         }); }; 

I already have my entry in database But the above code returns empty. Why?

EDIT : the following code also returns empty:

exports.listDoc = function(req, res) {     var Model = mongoose.model(req.query.model);     Model.find({},function(err,models){         console.log(models);          if (err) {             res.render('error', {                 status: 500             });         } else {             res.jsonp(models);         }     }); }; 

schema used :

var Organization = mongoose.Schema({   name: String }); 
like image 719
codeofnode Avatar asked Sep 05 '13 05:09

codeofnode


People also ask

What does model find return in Mongoose?

The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries. You don't instantiate a Query directly, Customer.

Does find return an array Mongoose?

find returns an array always.

What is Mongoose model ()?

A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Does Mongoose model create collection?

Mongoose never create any collection until you will save/create any document.


Video Answer


1 Answers

Your problem is mongoose pluralizes collections. Mongoose is querying "organizations" but your data is in mongodb as "organization". Make them match and you should be good to go. You can either rename it in mongodb via the mongo shell or tell mongoose about it. From the mongoose docs:

var schema = new Schema({ name: String }, { collection: 'actor' });  // or  schema.set('collection', 'actor');  // or  var collectionName = 'actor' var M = mongoose.model('Actor', schema, collectionName) 
like image 150
Peter Lyons Avatar answered Sep 16 '22 17:09

Peter Lyons