Tiocrash
Tiocrash

Reputation: 357

MongoDB array undefined in Javascript but present in database

I'm trying to push an ObjectId into an ObjectId array on another Object, but my array to hold objects comes back as undefined when trying to push to the array, even though it's present the a JSON dump:

enter image description here

 for (let i = 0; i < billedTimeEntries.length; i++) {
    const timeEntry = billedTimeEntries[i];
    const hourLog = await HourLog.find({ _id: timeEntry.hourLog });
    hourLog.timeEntries.push(timeEntry._id);

with the .push throwing a 'cannot read property of 'push' of undefined' even though the array is defined in the object supposedly.

My mongoose schema for this ObjectId array looks like this:

  timeEntries: [{
    type: mongoose.Schema.ObjectId,
    ref: 'TimeEntry',
  }],

And looks to be defined in the database as an empty array by default.

Upvotes: 0

Views: 1134

Answers (1)

andrii
andrii

Reputation: 1388

HourLog.find returns Query, and queries are not promises. Use Query#exec() method to get promise out of query and await on that promise. Furthermore, since you want to find single HourLog document, you should use findOne instead of find. This would fix things in your example:

const hourLog = await HourLog.findOne({ _id: timeEntry.hourLog }).exec();

Upvotes: 1

Related Questions