These are chat archives for Automattic/mongoose

3rd
Mar 2018
black09bb
@black09bb
Mar 03 2018 15:30
hello ,is there anyone? :D
Kev
@lineus
Mar 03 2018 15:52
what's up @black09bb ?
black09bb
@black09bb
Mar 03 2018 16:07

Do You know how to make this code asynchronous?

Here is normal version :

app.post('/musicianArray', (req, res) => {
    let tab = []
    let musicianArray = req.body.array
    musicianArray.forEach(musician => {
      return db.collection('Musicians').doc(musician).get().then(musician => tab.push(musician.data()))
    })
    res.json(tab)
  })

And here is await/async, but it's not working on Firebase Firestore ;c

  app.post('/musicianArray', async (req, res) => {
    asyncForEach = async function (array, callback) {
      for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array)
      }
    }
    let tab = []
    let musicianArray = req.body.array

    await asyncForEach(musicianArray, async(musician) => {
      await db.collection('Musicians').doc(musician).get().then(musician => tab.push(musician.data()))
    })
    return res.json(tab)
  })
Kev
@lineus
Mar 03 2018 16:35
I don't have any direct experience with firebase but having nested asynchronous callbacks hurts my simple brain :)
rather than looping over an array of musicians and making a call to get each document individually, it might be worth it
to call Model.find with an $in clause and an array of ids just once to return the set of matching documents.
Model.find({ '_id': { $in: musicianArray }}) assuming those are id's, if not you can pick the relevant path.
@black09bb that's the best idea I could come up with on the spot, maybe someone else will chime in if there's a better way, or if I'm just plain wrong :)
black09bb
@black09bb
Mar 03 2018 17:18

okay, for someone who wants to make something like this i've got a solution working :D

Sooo... we can user ForEP module from NPM , and then something like this :

  app.post('/musicianArray', (req, res) => {
  let tab = []
  let musicianArray = req.body.array

  forEP(musicianArray, (musician) => {
    return db.collection('Musicians').doc(musician).get().then(musician => tab.push(musician.data()))
  }).then(() => res.json(tab))
})
Kev
@lineus
Mar 03 2018 17:29
right on @black09bb. I'm glad you figured it out. I tested out my theory here and it worked too.
Kev
@lineus
Mar 03 2018 18:36
fwiw, if you'd rather solve it without installing more packages, this gist shows that Promise.all would get it done too.
Gustav Larsson
@gustavlrsn
Mar 03 2018 19:27
Anyone using Mongoose with GraphQL? I'm wondering if it's worth setting up relationships in the mongoose models or just solve the relationship stuff in the graphql resolvers