Creating and inserting a photo into the database

Now let’s create a new photo to save it in the database:

  1. import {createConnection} from "typeorm";
  2. import {Photo} from "./entity/Photo";
  3. createConnection(/*...*/).then(connection => {
  4. let photo = new Photo();
  5. photo.name = "Me and Bears";
  6. photo.description = "I am near polar bears";
  7. photo.filename = "photo-with-bears.jpg";
  8. photo.views = 1;
  9. photo.isPublished = true;
  10. return connection.manager
  11. .save(photo)
  12. .then(photo => {
  13. console.log("Photo has been saved. Photo id is", photo.id);
  14. });
  15. }).catch(error => console.log(error));

Once your entity is saved it will get a newly generated id.save method returns an instance of the same object you pass to it.It’s not a new copy of the object, it modifies its “id” and returns it.