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

2019-01-17 15:53发布

问题:

This question already has an answer here:

  • Mongoose always returning an empty array NodeJS 1 answer

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

回答1:

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)


回答2:

From official doc

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s).

Try it without populate

Model.find({}).exec(function(err, models) {
            if (err) {
                res.render('error', {
                    status: 500
                });
            } else {
                res.json(models);
            }
        });


回答3:

I will make Peter Lyons answer more simply , only add in mongodb collection name (s letter) . For example if you create collection which you want to call user or password , just write s letter in last of word (users,passwords) .