| Autor | Zpráva | ||
|---|---|---|---|
| KarelEben Profil |
Zdravím, mám tento kód
BuzzerListekSchema.statics.getBuzzerListekDetailPercentage = function(req, response, res){
// Funkce1
this.aggregate([
{$unwind: '$history'},
{$match: {'history.done': true}}, //Filtr
{$group: {_id: req.params.id, count: {$sum: 1}}}
], function(err, c){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
// Zde je výsledek c
// {_id: ubuiabiufbuiab, count: 5}
}
});
// Funkce2
this.aggregate([
{$unwind: '$history'},
{$group: {_id: req.params.id, count: {$sum: 1}}}
], function(err, c){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
// Zde je výsledek c
// {_id: ubuiabiufbuiab, count: 5}
}
});
//Zde chci získat procenta z funkce1/(funkce2/100) a poslat to JSON
//res.json({succes: false, msg: procenta});
};Jak dostat procenta jak mam v komentářích uvedené? Jinak vyvíjím v NodeJS + Mongoose pro obsluhu MongoDB |
||
| Radek9 Profil |
KarelEben:
Úplně přesně nevím, co myslíš těmi procenty, ale ty data se získávají asynchronně. Musíš tedy v obou z nich nějakým způsobem ověřovat, zda už ta druhá proběhla, a následně provést operaci nad daty. Celkem jednoduše to jde prostě přes funkci a dvě signalizační proměnné: BuzzerListekSchema.statics.getBuzzerListekDetailPercentage = function (req, response, res) {
let res1, res2;
// Funkce1
this.aggregate([
{$unwind: '$history'},
{$match: {'history.done': true}}, //Filtr
{$group: {_id: req.params.id, count: {$sum: 1}}}
], function(err, c){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
res1 = c;
processData();
}
});
// Funkce2
this.aggregate([
{$unwind: '$history'},
{$group: {_id: req.params.id, count: {$sum: 1}}}
], function(err, c){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
res2 = c;
processData();
}
});
function processData() {
if (!res1 || !res2) return;
// Tady pracuj s res1 a res2
}
};Pokud takové věci potřebuješ častěji, je lepší využít patterny a objekty k těmto věcem určené. Konkrétně mám na mysli Promise. Při použití balíčku denodeify je to vcelku triviální: let denodeify = require('denodeify');
BuzzerListekSchema.statics.getBuzzerListekDetailPercentage = function (req, response, res) {
let aggregate = denodeify(this.aggregate.bind(this));
Promise.all([
// Funkce1
aggregate([
{$unwind: '$history'},
{$match: {'history.done': true}}, //Filtr
{$group: {_id: req.params.id, count: {$sum: 1}}}
]),
// Funkce2
aggregate([
{$unwind: '$history'},
{$group: {_id: req.params.id, count: {$sum: 1}}}
])
])
.then(function (res) {
// Tady pracuj s res[0] a res[1]
})
.catch(function (err) {
res.status(500).json({succes: false, msg: 'Error'});
});
}; |
||
| Radek9 Profil |
Teď mi došlo, že Mongoose podporuje i Promise, pokud se aggregate nepředá callback. Obejdeš se tedy bez
denodeify, stačí v tom Promise.all volat jen this.aggregate([…]).
|
||
|
Časová prodleva: 10 let
|
|||
0