【问题标题】:Can't populate Mongoose schema on express route无法在快速路线上填充 Mongoose 架构
【发布时间】:2022-04-26 06:11:23
【问题描述】:

所以我想填充两个东西并在响应中返回它们,我想返回一个imagesauthor 的数组。但是,如果我排除 .populate() 方法,则响应不会返回任何内容,那么它会使用 ObjectId 正常返回。不确定是什么原因。我该如何调试这个,我做错了什么?

// Product Controller:
router.get('/:id', (req, res) => {
  Product.findById(req.params.id)
    .populate('author')
    .populate(['images'])
    .then(product => res.json({ success: true, product: product }))
    .catch(err => res.status(404).json({ success: false, err: err }));
});
// Product Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  images: [{
    type: Schema.Types.ObjectId,
    ref: 'Image',
  }],
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  }
});

module.exports = Product = mongoose.model('product', ProductSchema);
// Product document:
{
    "_id" : ObjectId("620ab784cde3e34263a9a3d9"),
    "images" : [ ObjectId("620ab784cde3e34263a9a3d6") ],
    "name" : "testing",
    "author" : ObjectId("5db8f65bb027c31ede3b64ae"),
    "__v" : 0
}

【问题讨论】:

    标签: mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您可以使用与单个 ObjectId 相同的语法来填充 ObjectId 数组。换句话说,删除.populate(['images']) 行周围的括号应该可以解决问题。像这样:

    //From:
    Product.findById(req.params.id)
        .populate('author')
        .populate(['images'])
    
    //To:
    Product.findById(req.params.id)
        .populate('author')
        .populate('images')
    

    此外,在您的模型文件中,您的模型引用中有一个上限,但填充没有。更改您的模型文件以匹配此,如果我没记错的话,Mongoose 将模型名称转换为小写,因此此处的 ref 可能正在寻找一个不存在的模型。像这样:

    //From:
    const ProductSchema = new Schema({
      name: {
        type: String,
        required: true,
      },
      images: [{
        type: Schema.Types.ObjectId,
        ref: 'Image',
      }],
      author: {
        type: Schema.Types.ObjectId,
        ref: 'User',
      }
    });
    
    //To:
    const ProductSchema = new Schema({
      name: {
        type: String,
        required: true,
      },
      images: [{
        type: Schema.Types.ObjectId,
        ref: 'image',
      }],
      author: {
        type: Schema.Types.ObjectId,
        ref: 'user',
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 2016-03-24
      • 1970-01-01
      • 2020-11-09
      • 2020-06-17
      • 1970-01-01
      • 2017-03-23
      • 2021-03-02
      • 1970-01-01
      相关资源
      最近更新 更多