Get firstName and lastName from Full Name persisted in MongoDB in Node.js
From the Mongoose
documentation,
Virtuals
Virtuals
are document properties that you canget
andset
but that do not get persisted toMongoDB
. Thegetters
are useful for formatting or combining fields, whilesetters
are useful for de-composing a single value into multiple values for storage.
As you have the name
property persisted in the DB, you should use getters
to split it as firstName
and lastName
whereas you can use setters
to define name
property from firstName
and lastName
.
So your code for virtuals
should be,
/* Returns the student's first name, which we will define * to be everything up to the first space in the student's name. * For instance, "William Bruce Bailey" -> "William" */schema.virtual('firstName').get(function() { var split = this.name.split(' '); return split[0];});/* Returns the student's last name, which we will define * to be everything after the last space in the student's name. * For instance, "William Bruce Bailey" -> "Bailey" */schema.virtual('lastName').get(function() { var split = this.name.split(' '); return split[split.length - 1];});