【问题标题】:NodeJS + Mongoose: saving a model and get back the ID to aggregate in another modelNodeJS + Mongoose:保存模型并取回 ID 以聚合到另一个模型中
【发布时间】:2020-01-31 14:37:04
【问题描述】:

我需要你的帮助。场地如下:

我有一个包含 3 种不同类别的产品目录。为了说明一个简单的例子,我得到了这个:

主电源”:

  • 水果和蔬菜
  • 肉类

子网”:

mainFruits & Vegetables”我得到了:

  • 水果
  • 蔬菜

然后是一堆“子类别”:

  • main肉类”内部:牛肉、猪肉、家禽
  • main”内:金枪鱼、鲑鱼
  • submainFruit”内部:香蕉、西瓜
  • submain蔬菜”内部:胡萝卜、豌豆

所以我创建了一个 3 步函数,首先获取“子类别”并将它们保存到特定的集合中,然后聚合 '_id' 和 main submain 它对应成一个数组。下面是代码的简化:

  const categories = {
    subMainCats: [{name: "fruit", ref: "4", family: "1"}, {name: "vegetables", ref: "5", family: "1"}],
    mainCats: [{name: "Fruits & Vegetables", ref: "1"}, {name: "meat", ref: "2"}, {name: "fish", ref: "3"}],
    subCats: [{name: "beef", fam: "2"}, {name: "pork", fam: "2"}, {name: "poultry", fam: "2"}, {name: "tuna", fam: "3"}, {name: "salmon", fam: "3"}, {name: "pork", fam: "5"}, {name: "peas", fam: "5"}, {name: "banana", fam: "4"}, {name: "watermelon", fam: "4"}]
  };

async function orderingDb(categories) {
  var subMains = categories.subMainCats;
  var mains = categories.mainCats;
  var subCats = categories.subCats;

  // Variables to recover info from elements that were added to db:
  var addedSubCats = [];
  var addedSubMains = [];

// Step 1: saving the subcats
await subCats.forEach(async (subCat, index) =>{
      const name =subCat.name;
      const fam = subCat.fam;

      // Creating the mongoose model object
      const subcat = new Subcategory({
        name: name,
        fam: main
      });

      // Saving to the db and adding the _id to the array
      await subcat.save().then(res => {
        console.log('saving subcat!');
        addedSubCats.push({
          main: main,
          _id: res._id
        });
      }).catch(err => console.log('ERROR: trying to save a subcat to mongo -- ', err));
  });

// Step 2: Adding the subcats and saving the submains
await subMains.forEach(async (subMain, index) => {
      const name = subMain.name;
      const fam = subMain.family;
      var subCats = [];

      // adding the subcats to the array
      addedSubCats.forEach((addedSubCat, index) =>{
        if(addedSubCat.main === subMain.category.subFamily) {
          subCats.push(addedSubCat._id);
          addedSubCats.splice(index);
        }
      });

      // Creating mongoose model object:
      const submain = new Submaincategory({
        name: name,
        subCats: subCats,
        main: main
      });

      // Saving and adding the _ids: 
      await submain.save().then(res => {
        console.log('saving submain');
        addedSubMains.push({
          main: main,
          _id: res._id
        })
      }).catch(err => console.log('ERROR: trying to save a Submain -- ', err ));
  });

 // ... FINALLY I'VE GOT THE SAME LOGIC FOR STEP 3 FOR THE MAINS.

}

这是我的问题:我的异步函数应该等待的 MODEL.save() 函数在函数的最后执行。这意味着当函数的其余部分被执行时,我的 addedSubCats addedSubMains 数组是空的......

提前致谢!

【问题讨论】:

    标签: node.js asynchronous mongoose


    【解决方案1】:

    问题的解决方法是在保存模型之前创建_id:

    const ObjectID = require('mongodb').ObjectID,
    const _id = new ObjectID();
    const fruit = new Fruit({_id, ...fruitBody})
    fruit.save(cb);
    
    // in this manner you will know in advance the _ids of the objects you will create
    // so you can populate the array of _ids to be aggregated later
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2019-06-23
      • 2015-02-27
      • 1970-01-01
      • 2020-05-18
      • 2021-03-26
      相关资源
      最近更新 更多