【问题标题】:Mongoose .populate() returning an empty arrayMongoose .populate() 返回一个空数组
【发布时间】:2021-09-16 11:25:55
【问题描述】:

对不起,我知道有很多问题都在问同样的问题,但我找不到任何可以为我解决问题的答案!

我正在尝试使用 mongoose 填充函数来填充模式的 ID,但它只返回一个空数组。如果我不使用填充函数,ID 就在数组中,但使用它似乎会删除它们。

我的路线和模型很简单,因为我只是想学习它,这对于为什么它错了更令人困惑!而且我认为我完全按照教程进行操作......

这些是我的架构:

var SeasonSchema = new Schema(
  {
    name: {type: String, required: true, enum: ['Spring', 'Summer', 'Autumn', 'Winter']},
    description: {type: String, maxLength: 300}
  }
);
var FruitSchema = new Schema(
  {
    name: {type: String, required: [true, 'All fruits have names.'], maxLength: 50},
    description: {type: String, maxLength: 300},
    season: [{type: Schema.Types.ObjectId, ref: 'Season', required: true}],
    price: {type: Number, min: 0, max: 9.99, required: true},
    stock: {type: Number, min: 0, max: 999, required: true}
  }
);

这是我要开始工作的控制器:(只需填充 Fruit's Season 字段。

exports.fruit_detail = function(req, res, next) {
    Fruit.findOne({name: req.params.name})
    .populate('season')
    .exec(function (err, fruit) {
      if (err) {return next(err);}
      if (fruit==null) {
        var err = new Error('Fruit not found');
        err.status = 404;
        return next(err);
      }
      res.render('fruit_detail', {title: fruit.name, fruit: fruit});
    });
};

感谢您的帮助。我已经束手无策了。

【问题讨论】:

    标签: node.js express mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    .populate()是一个异步方法,需要正确调用:

    exports.fruit_detail = async function(req, res, next) {
      await Fruit.findOne({name: req.params.name})
        .populate('season')
        .execPopulate(function (err, fruit) {
          if (err) {return next(err);}
          if (fruit==null) {
            var err = new Error('Fruit not found');
            err.status = 404;
            return next(err);
          }
          res.render('fruit_detail', {title: fruit.name, fruit: fruit});
        });
    };
    

    然后你必须导入你的 fruit_deail 方法并异步调用它:await this.fruit_detail(req, res, next)

    【讨论】:

    • 等等,我在哪里导入它?
    • 好吧,我猜你是在某个地方导出fruit_detail,不是吗?
    • 我这么认为?在路由文件中? router.get('/fruit/:name', fruit_controller.fruit_detail); 对不起,我真的以为我已经掌握了这个,但我想没有!
    • 别担心 :) 你在哪里定义你的fruit_detail 控制器?
    • 我有一个index.js 路由router.get('/fruit/:name', fruit_controller.fruit_detail);,它导入了包含上述fruit_detail 函数的fruitController
    【解决方案2】:

    大量的手掌表情符号。

    问题是所引用的季节 ID 来自不存在的季节。我在填充数据库时不知何故做了重复,我删除了错误的。感觉自己浪费了两天的生命,但至少它已经整理好了!

    【讨论】:

      猜你喜欢
      • 2013-12-17
      • 2015-08-16
      • 1970-01-01
      • 2013-05-22
      • 2016-12-24
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多