【问题标题】:Model.find() returns empty in mongoose [duplicate]Model.find() 在猫鼬中返回空 [重复]
【发布时间】:2013-09-08 20:02:33
【问题描述】:

我正在研究 mongoose 以列出 mongodb 数据库中集合中的所有数据:

来自请求:

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

我正在执行以下代码:

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

我已经在数据库中输入了我的条目 但是上面的代码返回空。为什么?

编辑:以下代码也返回空:

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

使用的模式:

var Organization = mongoose.Schema({
  name: String
});

【问题讨论】:

  • 我没有看到您的代码 sn-p 有任何明显问题。您可以发布您的组织架构吗?您的集合在 mongodb 中是否称为“组织”?
  • 我已经添加了使用的架构
  • 看起来还可以。连接 mongodb 时是否连接到正确的数据库名称?
  • 你怎么知道你在数据库中有一个条目?该系列的名称是什么?
  • 集合名称:组织,它有文件,我可以从 mongo shell 中看到

标签: node.js mongodb express mongoose


【解决方案1】:

来自官方doc

填充是自动替换指定的过程 文档中的路径以及来自其他集合的文档。

无需填充即可尝试

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

【讨论】:

  • 这也返回空..
  • 试试res.json(models)
  • 再次返回空
【解决方案2】:

您的问题是 mongoose 将集合复数化。 Mongoose 正在查询“组织”,但您的数据在 mongodb 中作为“组织”。让它们匹配,你应该很高兴。您可以通过 mongo shell 在 mongodb 中重命名它,或者告诉 mongoose。来自猫鼬文档:

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

// or

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

// or

var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)

【讨论】:

  • 非常感谢...我花了几个小时来研究为什么我总是得到一个空数组。
  • +1。如此简单的错误会吞噬你所有宝贵的时间......
  • 这么小的错误,但我花了很长时间才找到它。我已经准备好写 SO 问题了,在类似的问题中我发现了这个。
  • 多么烦人的功能。谢谢回答
  • 我用下划线命名集合,但我不知道这也会导致问题
猜你喜欢
  • 1970-01-01
  • 2015-08-04
  • 2016-06-20
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多