node.js - 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()函数在函数的最后执行。这意味着当函数的其余部分被执行时,我的addedSubCats和addedSubMains数组是空的......
提前致谢!
解决方案
该问题的解决方案是在保存模型之前创建_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
推荐阅读
- linux - 如何在 Bash 中将字符串格式日期 yyyymmddThhmmss.sss 转换为日期?
- python - 使用 python 验证自定义邮件 ID
- mongodb - 使用对字段值的引用进行聚合中的 Mongodb 正则表达式
- excel - 我如何组合/透明的分离数据
- python-2.7 - scipy.integrate 中的 Odeint 函数给出了错误的结果
- android - 为什么 Android Service 和 Activity 在主线程中异步执行
- jquery - 如何在不覆盖另一个的情况下链接插件 CSS 和普通 CSS?
- spring-boot - Spring boot 中的 JSF @ViewAccessScoped 等效项
- reactjs - 如何在反应 js 中为每次单击按钮显示输入字段?
- java - 从 java 扩展中读取事物的属性值