Referencing an array fails because of Asynchronous calls

I am trying to reference a document in MongoDB. I am trying to first create the document I want to insert before actually calling the database. I have used

const venues = [
  new Venue({ name: 'A' }),

const events = [
  new Event({
    name: 'B',
    venue: venues[0]._id

but it seems venues[0]._id is null.

If I use console.log(venues), I do get the array I want, so it shouldn’t say null.

I’m afraid this happens due to asynchronous calls, i.e. that the const venues = … line is not done before it starts the const events = … line of code.

What can I do to ensure const venues = … is done before referencing the array in the next line?


Actually, if I use console.log(events), I see that it works as it should.

But when I use

Promise.all([Venue.create(venues), Event.create(events)]).then(() => { .. });

the venue becomes null.

Your code is missing the part where you ACTUALLY save the Venue object to the DB (meaning some call to MongoDB’s insert function). Unless you save it, or manually provide an _id property, that property will stay undefined. This has nothing to do with synchronous/asynchronous code.


When you assign venues[0]._id to the venue property of the new Event object it is undefined because you haven’t called the create function yet. What you should do is:

  1. Create the Venue object in the DB
  2. Upon completion, assign the newly created _id.

Waiting for completion can be done in numerous ways:

  1. Using a callback
  2. Using the .then(…) function of a Promise
  3. awaiting a promise

It all really depends on your flavor and on the tools you are using.

And most importantly, notice that Promise.all will execute all the promises in the array at once, so you can’t use that in this case.