gstore-node
Search…
virtual()
Virtuals are properties that are added to the entities at runtime that are not persisted in the Datastore. You can both define a getter and a setter.

getter

1
const userSchema = new Schema({
2
firstname: {},
3
lastname : {}
4
});
5
6
userSchema.virtual('fullname').get(function fullName() {
7
// the scope (this) is the entityData of the entity instance
8
// for this reason don't use arrow functions here
9
return `${this.firstname} ${this.lastname}`;
10
});
11
12
const User = gstore.model('User', schema);
13
14
const user = new User({ firstname:'John', lastname:'Snow' });
15
console.log(user.fullname); // 'John Snow';
16
17
/*
18
* You can also set virtuals to true when calling plain() on your entity
19
* to add them to the object returned.
20
*/
21
const response = user.plain({ virtuals: true });
22
console.log(response.fullname); // 'John Snow';
Copied!

setter

1
const userSchema = new Schema({
2
firstname: {},
3
lastname : {}
4
});
5
6
userSchema.virtual('fullname').set(function(name) {
7
const split = name.split(' ');
8
this.firstname = split[0];
9
this.lastname = split[1];
10
});
11
12
const User = gstore.model('User', schema);
13
14
const user = new User();
15
user.fullname = 'John Snow';
16
17
console.log(user.firstname); // 'John';
18
console.log(user.lastname); // 'Snow';
Copied!
Note: You can save entities without worrying about the virtuals as they are removed from the entity data automatically.
Last modified 2yr ago
Copy link
Contents
getter
setter