在mongoose node.jhs中按引用筛选

vnjpjtjt  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(107)

我遇到了以下情况,我需要更好地了解人口是如何工作的:我有3个模式如下。我需要过滤子模式的基础上祖父属性名称。我创建了一个填充前发现,但看起来像填充没有帮助过滤的基础上属性,而只有对象ID。控制器代码如下所示:

filter= {childname: req.params.childname, 'child.parent.grandparent.grandparentname': req.params.grandparent};
const result =  await Child.find(filter)

const childSchema = new mongoose.Schema(
    {
        childname: {
            type: String,
         
    
          },
       
          
          parent:{
            type:mongoose.Schema.ObjectId,
            ref: 'Parent',
            required: [true, "Parent missing"],
           // select: false
    
           }
           
        
    },
    { timestamps: true },
    {
      toJSON: { virtuals: true },
      toObject: { virtuals: true }
    }
);
childSchema.pre(/^find/, function(next) {
  
    this.populate
         (
            {path: 'parent',select: '-__v',
           populate: [
                { path: 'grandparent', select: 'grandparentname' }
                
              ]
    
      
 });
    
  next();
       });
    
  
 const Child = mongoose.model( 'Child', childSchema);
  
 module.exports = Child;

const parentSchema = new mongoose.Schema(
    {
      
          parentname: {
            type: String,
    
          },
          grandparent:{
            type:mongoose.Schema.ObjectId,
            ref: 'grandparent',
            required: [true, "Grand parent missing"],
           // select: false
    
           },
           
        
    },
    { timestamps: true },
    {
      toJSON: { virtuals: true },
      toObject: { virtuals: true }
    }

 );

   const Parent = mongoose.model( 'Parent', parentSchema);
  
  module.exports = Parent;
  
  
  const grandparentSchema = new mongoose.Schema(
    {
      
          grandparentname: {
            type: String,
    
          }
      
         
           
        
    },
    { timestamps: true },
    {
      toJSON: { virtuals: true },
      toObject: { virtuals: true }
    }

 );
    
  
    const Grandparent = mongoose.model( 'Grandparent', grandparentSchema);
  
  module.exports = Grandparent;
vsdwdz23

vsdwdz231#

我有答案了!
首先-删除您的Childschema.pre('^/find...
并使用下一个代码:

const result = await Child.aggregate([{
    $match: {
      childname: YOUR_CHILDNAME_VARIABLE,
    }
  }, {
    $lookup: {
      from: 'parents',
      localField: 'parent',
      foreignField: '_id',
      as: 'parent',
      pipeline: [
        {
          "$lookup": {
            "from": "grandparents",
            localField: "grandparent",
            foreignField: "_id",
            "as": "grandparent"
          },
        }, {
          $unwind: '$grandparent'
        },
      ]
    }
  }, {
    $unwind: '$parent'
  }, {
    "$match": {"parent.grandparent.grandparentname": YOUR_GRANDPARENTNAME_VAIRABLE}
  }]);

我试着用populate来做,但是没有结果:(所以,我用aggregate找到了解决方案,它起作用了!)

相关问题