0

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.

3
  • 1
    have you tried const hourLog = await HourLog.findOne({ _id: timeEntry.hourLog }).exec(); ? Commented Jul 16, 2018 at 23:11
  • That works perfectly, missed that promise implementation. Commented Jul 16, 2018 at 23:34
  • ok, posted detailed answer on your question Commented Jul 16, 2018 at 23:35

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

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.