trainer.mons.forEach(function(id) {
Mon.findOne({monId: id}, (err, found) => {
desc += "\n "+ found.name
});
});
Hello, please have a read at how to ask.
i have no other way of explaing it,
So there is a collection named trainer, and mon in mongodb
and the trainer schema goes like
_id: id-stuff,
name: String,
mons: [Array]
and the mon goes like
_id: id-stuff,
monId: Number,
name: String
so i want to .forEach the trainer.mons and find the mon.name for every monId in mons: [Array]
wild guess: Mon.findOne
is async and you’re looking at desc
synchronously on the next line
Well technically you could try to prevent the event loop from continuing until the promise has been resolved, I guess you could try using generators.
Well, I dont think that it is unsafe to do assignments to desc
until it’s wrapped within callback, @wh0 . That’s the way node works?
Why isnt this working?
Trainer.findOne({ id: message.author.id }, (err, trainer) => {
var fmons =
trainer.mons.forEach(function(id){
Mon.findOne({monId:id}, (err, fmon) => {
fmons.push(fmon.name)
})
})
console.log(fmons)
})
As per your described schemas, id
isn’t a key in trainer (post) or Trainer (code).
Btw, I don’t know if trainer.mons.forEach()
works. Though, trainer.find({_id: 0, mons: 1}).toArray(callback)
would work.
Let’s start with something that better isolates the behavior. Tell me what you think of this code:
var fmons = [];
setTimeout(() => {
fmons.push('jake');
}, 1000);
console.log(fmons);
Im using mongoose,
Trainer.find({}).then(function(users) {
var mons = [];
users.forEach(function(u) {
mons.push(Mon.find({owner: message.author.id}));
});
return Promise.all(mons);
}).then(function(found) {
message.channel.send(found[0])
}).catch(function(error) {
console.log('one of the queries failed', error);
});
and this gives me result as,
{
id: "1"
name: "Name"
}
but when i do found[0].name
it says undefined
Thats just to push jake in fmons aint it.
yeah, but you understand what happens when, and you understand what it logs, right?
yes it logs the data inside of { } but according to my knowledge its supposed to work when found[0].name is used
would you mind showing where in the code snippet you’ve been putting the found[0].name
?
there in message.channel.send where its found[0]
i used found[0].name
After Promise.all
oh well then I don’t have any ideas specific to that.
short of walking through it with a debugger, maybe printing both found[0]
and found[0].name
would shed some light
its fine because of this i have stopped this project and im on a diff so this was the last hope, but i was still gonna leave it cuz its just hard for me cuz im self taught so ty for that