猫鼬填充不能在带有“路径”选项的子文档数组中工作

问题描述

这是我的猫鼬模式:

const productSchema = mongoose.Schema({
  writer: {
        type: Schema.Types.ObjectId,ref: 'User'
  },schedule: [{
            dateTime: {
                type: String,unique: 1            
            },candidates: [{
                type: Schema.Types.ObjectId,ref: 'User'
            }],attorn: {
                type: Schema.Types.ObjectId,ref: 'User'
            }
        }]
   ...

这是我和候选人一起拿到我的物品的地方:

    Product.find({ '_id': { $in: productIds } })
    .populate('writer')
    .populate({ 
        path: 'schedule',populate: {
          path: 'candidates',model: 'User'
        } 
     })
    .exec((err,product) => {
        if (err) return res.status(400).send(err)
        return res.status(200).send(product)
    })
  1. 代码的结果是一个产品,其中只填充了“writer”,而“candidates”则为空数组
  2. 如果我删除用于填充“候选人”的行,它会为“候选人”返回 _id 数组
  3. 如何填充 'candidates' 数组?

解决方法

你可以试试这个吗

Product.find({ _id: { $in: productIds } })
  .populate("writer")
  .populate({
    path: "schedule.candidates",})
  .populate({
    path: "schedule.attorn",})
  .exec((err,product) => {
    if (err) return res.status(400).send(err);
    return res.status(200).send(product);
  });