首页 > 解决方案 > NodeJS + Mongoose:保存模型并取回 ID 以聚合到另一个模型中

问题描述

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

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

电源”:

  • 水果和蔬菜

子网”:

主要的“水果和蔬菜”中,我得到了:

  • 水果
  • 蔬菜

然后是一堆“子类别”:

  • 里面主要的“”:牛肉、猪肉、家禽
  • 里面的主要”:金枪鱼、鲑鱼
  • 子主水果”内部:香蕉、西瓜
  • 在子主目录蔬菜”中:胡萝卜、豌豆

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

  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()函数在函数的最后执行。这意味着当函数的其余部分被执行时,我的addedSubCatsaddedSubMains数组是空的......

提前致谢!

标签: node.jsasynchronousmongoose

解决方案


该问题的解决方案是在保存模型之前创建_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

推荐阅读