Creating and inserting a photo into the database
Now let’s create a new photo to save it in the database:
import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";
createConnection(/*...*/).then(connection => {
let photo = new Photo();
photo.name = "Me and Bears";
photo.description = "I am near polar bears";
photo.filename = "photo-with-bears.jpg";
photo.views = 1;
photo.isPublished = true;
return connection.manager
.save(photo)
.then(photo => {
console.log("Photo has been saved. Photo id is", photo.id);
});
}).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.