【问题标题】:Filter in pre (find) hook Mongoose在预(查找)钩子 Mongoose 中过滤
【发布时间】:2023-02-18 02:03:33
【问题描述】:

我正在尝试执行一个从另一个文档中过滤数组的查询,为了提及结构,我尝试根据指定的产品和商店 ID 填充文档,这样它就不会从数组,但在这种情况下,我知道在中间件中我无法访问文档字段,我正在阅读文档,但我仍在学习概念

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

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

  next();
});

任何指南都会有很好的帮助

我尝试这样的事情

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();
});

但给我

商店未定义

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    我可以解决它,我使用 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,
            },
          });
        }
      }
    });
    
    

    如果有人有更好的主意,将不胜感激。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-23
      • 2021-04-19
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多