Expose mongoose models via Node.js REST service -


there following schemas:

var quest = new schema({     name: { type: string, required: true } });  var attempt = new schema({     quest: { type: objectid, ref: 'quest' },     success: { type: boolean, required: true, default: false } });  var person = new schema({     name: { type: string, required: true },     attempts: [attempt] }); 

we have list of quests , list of people. every time person attempts pass quest, create attempt entry.
nice expose person via rest service so, have list of empty attempts containing attached attempts plus 1 attempt every quest wasn't attempted.

i've ended having this:

router.get('/people/:id', function(req, res) {     return peoplemodel.findbyid(req.params.id, function (err, person) {         if(!person) {             ....         }         if (!err) {             return questsmodel.find(function (err, quests) {                 if (!err) {                     var result = person.attempts;                     quests.foreach(function(quest){                         var attempt = person.attempts.find(attempt=>{attempt.quest == quest._id});                         if(!attempt)                         {                           var newattempt = {                                 quest: quest,                                 success: false                           };                           result.push(newattempt);                         }                         else {                           result.push(attempt);                         }                     });                     person.attempts = result;                     return res.send({ status: 'ok', person:person });                 } else {                    ...                 }             });         } else {             ...         }     }); }); 

that doesn't feel right. there common practice such situations? maybe kind of mapping.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -