【问题标题】:Mongoose query not returning values猫鼬查询不返回值
【发布时间】:2018-03-07 12:38:33
【问题描述】:

我有一个名为 plotCasts 的 CosmosDB 集合,它的对象如下所示:

{ ... "owner" : "winery", "grower" : "Bill Jones", ... }

我有以下 Mongoose 架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const plotCastSchema = new Schema({
    owner: String,
    grower: String,
   ...
});

const ModelClass = mongoose.model('plotCast', plotCastSchema);

module.exports = ModelClass;

但是,当我使用下面的查询查询数据库时,我得到一个空数组作为结果。知道为什么吗?

PlotCast.find({ owner: 'winery' }).lean().exec(function(err, results) {
                if (err) {
                    res.send(err);
                } else if (!results) {
                    res.send(null);
                } else {
                    res.send(results);
                }
            });

【问题讨论】:

  • 酒厂包含的数据库不存在,这就是它出现空数组的原因
  • @RaviTeja 我不明白-你是什么意思?有一个情节广播,其中关键的“所有者”具有“酒厂”的价值。

标签: node.js mongodb mongoose


【解决方案1】:

好的,您将模型命名为 plotCast,但您的集合是 plotCast。

您可以通过这种方式强制您的集合名称:

const plotCastSchema = new Schema({
    owner: String,
    grower: String,
    ...
}, { collection: 'plotCasts' });

或者,只需在 mongoose 中定义您的模型,并将集合名称作为第一个参数,这样:

const ModelClass = mongoose.model('plotCasts', plotCastSchema);

如果是这样,请告诉我:)

【讨论】:

  • 行得通!谢谢你。那么以后模型的文件名应该和集合的文件名一样吧?这很奇怪,因为在我的用户架构中,我使用了名称“用户”,而集合名称为“用户”,并且工作正常。
  • 这与文件名无关,它与传递给mongoose.model('plotCast', plotCastSchema); 的第一个参数有关,这里是plotCast,这是错误的,因为集合是plotCasts,但如果你愿意,可以如我在答案中所示,在模式中设置集合名称。
【解决方案2】:

问题是命名数据库总是以复数形式保存模式,所以它应该如下所示

PlotCasts.find({ owner: 'winery' }).lean().exec(function(err, results) {
            if (err) {
                res.send(err);
            } else if (!results) {
                res.send(null);
            } else {
                res.send(results);
            }
        });

【讨论】:

  • 这就解释了!
猜你喜欢
  • 2019-09-29
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2020-06-02
  • 2018-05-26
  • 2022-11-22
相关资源
最近更新 更多