sto lavorando a un progetto Meteor e devo dire che non è affatto facile, soprattutto per una cosa: le richiamate!Meteor: non più richiamate per la funzione "findOne"
Tutto è asincrono, quindi mi chiedo come devo fare per ottenere i risultati dal mio mongodb.
var user = Meteor.users.findOne({username: "john"});
return (user); // sometimes returns "undefined"
...
var user = Meteor.users.findOne({username: "john"});
if (user) // so ok, I check if it exists!
return (user); // Cool, I got my user!
return(); // Ok and what should I return here? I want my user!
Non voglio essere sporco e mettere come setTimeout ovunque. Qualcuno ha una soluzione per questo?
EDIT: ho notato in router.js con console.log che il mio dati vengono restituiti 4 volte. 2 volte con un valore non definito e altre 2 volte con il valore previsto. Nella vista, è ancora indefinito. Perché il router passa 4 volte in questo percorso? Mostra il primo risultato del valore di ritorno nel router?
Cosa devo restituire se find() non trova nulla?
EDIT 2: Ecco il codice per capire.
this.route('profilePage', {
path: 'profil/:_id?',
waitOn: function() {
return [
Meteor.subscribe('article', { prop: this.params._id}), // id can be id or username
Meteor.subscribe('article', { userId: this.params._id}), // id can be id or username
Meteor.subscribe('params'),
Meteor.subscribe('profil', (this.params._id ? this.params._id : Meteor.userId()))
];
},
data: function() {
if (this.params._id) {
var user = Meteor.users.findOne(this.params._id);
if (!user)
user = Meteor.users.findOne({username: this.params._id});
console.log(user);
return user;
}
else if (Meteor.userId())
return Meteor.user();
else
Router.go("userCreate");
}
});
ottengo questo sulla console: http://puu.sh/debdJ/69419911f7.png
(versione testo riportato di seguito)
undefined
undefined
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Sono abbastanza sicuro che 'findOne' non è asincrono e il tuo primo esempio dovrebbe andare bene. Presumo che tu stia facendo questo sul client, vuoi essere sicuro che l'utente che stai cercando si trovi nella tua raccolta lato client. Nella console del tuo browser esegui 'Meteor.users.findOne ({username:" john "})' e questo dovrebbe togliere la sincronizzazione dalla domanda. – Shaded
findOne dovrebbe essere sincrono e reattivo. Stai dicendo che a volte ritorna indefinito anche quando la query deve restituire un valore? Nota, generalmente uso findOne con un _id in modo che possa essere parte del motivo per cui provo un comportamento diverso. –
@LarryMaccherone Sì, è tutto. Restituisce indefinito dove dovrebbe restituire qualcos'altro. E ho notato con console.log che i miei dati in routes.js vengono restituiti 4 volte: 2 volte con undefined e 2 volte con l'oggetto che mi aspetto. Ma nella vista, l'oggetto non è definito. – Sw0ut