2

Initially I have an empty array inside of the file, but during the code execution I get data from the database and push the data to an array. My code looks like this:

items.js

const items = [];

const init = (connection) => {
  return connection.collection('collectionName')
    .aggregate([{
      ....
    
    }])
    .toArray()
    .then(result => {
      items.push(...result);
      return result;
    });     
};

module.exports = {
  init,
  all: items,
  item1: items[0],
  item2: roles[1],
};

And when I try to import all, item1 and item2 using require in a different file like this:

const { all, item1, item2 } = require('../data/items');

I get the array with object as all, but get undefined for item1 and item 2. I can't seem to understand what the issue is. I know I can use an anonumous function when exporting and get the data this way, but I would rather do it by trying to access the data from an array by element's index. All the help is much apprecieted!

1 Answer 1

1

I get the array with object as all

Given that code, you shouldn't. Presumably you call init at some point though.

but get undefined for item1 and item 2. I can't seem to understand what the issue is.

At the time you read items[0] to assign it to the object you are exporting, the asynchronous function hasn't completed so the array is still an empty array.

You could replace item1 with a getter that gets the current value of items[0] at the time you try to read the item1 property, but that would be likely to still land you with race conditions.

The better solution is probably to export a promise that evaluates as the object once the fetch is complete.

Obviously you will then need to use then() or await on the exported value. You won't get the object directly from the import.

const init = async (connection) => {
    const items = await connection.collection('collectionName')
    .aggregate([{
      ....
    
    }])
    .toArray()
    return {
        all: items,
        item1: items[0],
        item2: roles[1], // whatever roles is
    }
};

module.exports = init();

and

const promise = require('../data/items');
const { all, item1, item2 } = await promise;
Sign up to request clarification or add additional context in comments.

1 Comment

I see your point, unfortunately your approce won't work how I need it to work, because when I'm importing item1 for example, I need to use it like so: $setOnInsert: { item: item1.name] } I will probably have to use a getter, but thank you anyway, helped me understand the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.