Search code examples
node.jsmongodbmongoosemongoose-populate

Filter in pre (find) hook Mongoose


I'm trying to perform a query that filters an array from another document, to mention something about the structure, I try to populate the document based on the specified product and store id, so that it doesn't bring the other data from the array but in this case I understand that I can't access the document fields while in the middleware, I'm reading the documentation but I still learning concepts

bUnitSchema.pre(/^find/, function (next) {
  
  this.populate({
    path: "menuItem.product",

    select: {
      "storeId.$": 1,
    },
    match: {
      "storeId.store": "62a811d1af67f5415770f297",
      
    },
  });

  next();
});

any guide would be of excellent help

I try something like this

bUnitSchema.pre(/^find/, function (next) {
  
  this.populate({
    path: "menuItem.product",

    select: {
      "storeId.$": 1,
    },
    match: {
      
       *//here im trying to do something like this*
      *"storeid.store": bUnitSchema.menuItem.store*
    },
  });

  next();
});

but give me

store not defined


Solution

  • I can solve it, i use a post hook :

    bUnitSchema.post(/^find/, async function (docs) {
      for (let doc of docs) {
        for (let store of doc.menuItem) {
          await doc.populate({
            path: "menuItem.product",
            select: {
              image: 1,
              imagePath: 1,
              plateFor: 1,
              description: 1,
              name: 1,
              _id: 1,
              "storeId.$": 1,
            },
            match: {
              "storeId.store": store.store,
            },
          });
        }
      }
    });
    
    

    If anyone has a better idea, it would be appreciated.