我有一个相当复杂的数组结构,其中包含4个需要使用Mongoose / MongoDB处理的嵌套数组。我的代码有效,但是没有获得美金奖。
现在我有一个帮助函数,该函数将查找所述ID的对象,如果没有,则将$ addToSet并返回数组以进行进一步操作。感觉确实很笨拙,我敢肯定,某些查询向导会在一个简单的findOneAndUpdate()中解决此问题。
对象结构如下: 书架作为数组 具有ID和名为Categories的数组的Branch Object 具有ID的类别对象和一个名为Learnings的数组 具有ID和名为Modules的数组的Learnings对象 具有ID和名为Cards的数组的Modules对象
之所以这样设置,是因为集合在关系方面是一种方向,并且文档没有父级。因此,出于书签功能的考虑,我将存储整个路径。因此,一个模块中可能有几张卡。
// TODO can probably do this in some advanced query
addtobookshelf: async function (req, res, next) {
if(!req.body.branch)
return next(boom.badRequest('No Branch id supplied.'));
if(!req.body.category)
return next(boom.badRequest('No Category id supplied.'));
if(!req.body.learning)
return next(boom.badRequest('No Learning id supplied.'));
if(!req.body.module)
return next(boom.badRequest('No Module id supplied.'));
if(!req.body.card)
return next(boom.badRequest('No Card id supplied.'));
try{
const saveslot = await SaveSlot.findOne({'owner':req.decoded._id});
let branchObject = profile.manipulateBookmark(saveslot.bookshelf, req.body.branch);
let categoryObject = profile.manipulateBookmark(branchObject.categories, req.body.category);
let learningObject = profile.manipulateBookmark(categoryObject.learnings, req.body.learning);
let moduleObject = profile.manipulateBookmark(learningObject.modules, req.body.module);
// Finally add the card
moduleObject.cards.addToSet(req.body.card);
await saveslot.save();
return res.status(200).json({message: 'succes', data: saveslot.bookshelf});
} catch(err){
console.log(err);
return next(boom.internal('Woops, something went wrong. Sorry!'));
}
},
manipulateBookmark: function(objectArray, id){
let obj;
objectArray.forEach((element) => {
if(element.id.toString() === id){
obj = element;
return;
}
});
if(!obj){
obj = objectArray.addToSet({id:id})[0];
}
return obj;
},
它可读,所以很重要,但我想提高查询技能。
[EDIT]添加了用于澄清的数据结构
{
"bookshelf": [{
"id": "59034709d44f340011bb8307",
"categories": [{
"id": "58c27aa7734d1d46588667ab",
"learnings": [{
"id": "5881d1f62fd76911007a4ae5",
"modules": [{
"id": "5881d2962fd76911007a4ae8",
"cards": ["5881d5892fd76911007a4ae1"]
}]
}]
}]
}]
}