Save a one-to-one relation

Now let’s save a photo, its metadata and attach them to each other.

  1. import {createConnection} from "typeorm";
  2. import {Photo} from "./entity/Photo";
  3. import {PhotoMetadata} from "./entity/PhotoMetadata";
  4. createConnection(/*...*/).then(async connection => {
  5. // create a photo
  6. let photo = new Photo();
  7. photo.name = "Me and Bears";
  8. photo.description = "I am near polar bears";
  9. photo.filename = "photo-with-bears.jpg";
  10. photo.isPublished = true;
  11. // create a photo metadata
  12. let metadata = new PhotoMetadata();
  13. metadata.height = 640;
  14. metadata.width = 480;
  15. metadata.compressed = true;
  16. metadata.comment = "cybershoot";
  17. metadata.orientation = "portait";
  18. metadata.photo = photo; // this way we connect them
  19. // get entity repositories
  20. let photoRepository = connection.getRepository(Photo);
  21. let metadataRepository = connection.getRepository(PhotoMetadata);
  22. // first we should save a photo
  23. await photoRepository.save(photo);
  24. // photo is saved. Now we need to save a photo metadata
  25. await metadataRepository.save(metadata);
  26. // done
  27. console.log("Metadata is saved, and relation between metadata and photo is created in the database too");
  28. }).catch(error => console.log(error));