'Mongoose one to many relationships (user and photos) - unable to save user with stored photo id after creating a photo

I have a users model and a photos model. I am currently trying to create a photo, using session and a transaction, within a try catch block to save the created photo, push the photo id to the user object, and then save the user object.

However, it keeps going to the catch block after hitting "await user.save({ session: sess });"

I've console logged the user object, after pushing the photo object to the user and it is definitely getting pushed to the photos array within the user.

here is the try block.

try {
  const sess = await mongoose.startSession(); 
  sess.startTransaction();
  await createdPhoto.save({ session: sess });
  user.photos.push(createdPhoto); 
  await user.save({ session: sess });
  console.log('test')
  await sess.commitTransaction();
}

This is what the photos key value pair looks like within the user schema.

photos: [{ type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Photo' }]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source