After you create an entity you can persist its data to the Datastore with entity.save()
This method accepts the following arguments
entity.save(/* {Transaction} -- optional. Will execute the save operation inside this transaction */ <transaction>, /* {object} -- optional. Additional config */ <options>, /* {function} --optional. The callback, if not passed a Promise is returned */ <callback>)
@Returns -- the entity saved
options
The options argument has a method property where you can set the saving method.
It default to 'upsert'.
// blog-post.controller.jsconstBlogPost=require('./blog-post.model');constdata= { title:'My first blog post' };constblogPostEntity=newBlogPost(data);blogPostEntity.save().then((entity) => {console.log(entity.entityKey.id); // auto-generated id}).catch(err => { ... });// changing the save methodvar blogPostEntity =newBlogPost(data);blogPostEntity.save(null, { method:'insert' }).then( ... );// with a callbackblogPostEntity.save(functiononBlogPostSave(err, entity) {if (err) { // deal with err }console.log(entity.entityKey.id); // auto-generated id});// from inside a transaction// Info: if you have middleware on "pre" see note belowconsttransaction=gstore.transaction();transaction.run().then(() => {constblogPost=newBlogPost({ title:'My new blog post' });blogPost.save(transaction);// ... any other operation on the Transactionreturntransaction.commit(); }).then((response) => {// ... transaction finishedconstapiResponse= data[0]; }).catch((err) => {// handle error });
Saving inside a Transaction with middleware on Model
If you have "pre" middlewares on the save method of your Model (mySchema.pre('save', myMiddleware)) you need to chain the Promise of the save method before committing the transaction, otherwise the entity won't be saved.
You can avoid this by disabling the middlewares on the entity with preHooksEnabled set to false on the entity.
Examples:
constuser=newUser({ name:'john' });consttransaction=gstore.transaction();// option 1: chaining Promise before committingtransaction.run().then(() => {returnuser.save(transaction) // there are some "pre" save hooks.then(() => {// need to chain Promise before committingreturntransaction.commit(); }); }).then((response) => {constapiResponse= data[0];// ... transaction finished }).catch((err) => {// handle error });// option 2: disable "pre" middlewares on entity before savingtransaction.run().then() => {User.get(123,null,null, transaction).then((entity) => {entity.email ='john@domain.com';// validate before so we can rollback the transaction if necessaryconstvalid=user.validate();if (!valid) {// rollback the transaction; }// disable pre middleware(s)user.preHooksEnabled =false;// save inside transaction in "sync"user.save(transaction);// ... any other transaction operationstransaction.commit().then(() => {... }); });});