Get firstName and lastName from Full Name persisted in MongoDB in Node.js Get firstName and lastName from Full Name persisted in MongoDB in Node.js mongoose mongoose

Get firstName and lastName from Full Name persisted in MongoDB in Node.js


From the Mongoose documentation,

Virtuals

Virtuals are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters 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];});