Reputation: 55
I am trying to get separate firstName and lastName from the FullName for learning purpose. When I go to run this application I get two error a)Mongoose Schema Student has a 'firstName' virtual b) Mongoose Schema Student has a 'lastName' virtual
Below is the code I am debugging
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
name: { type: String, required: true },
courses: [{ type: String, ref: 'Course' }]
});
/* 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').set(function(name) {
var split = name.split(' ');
this.firstName = 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').set(function(name) {
var split = name.split(' ');
this.lastName = split[split.length - 1];
});
module.exports = schema;
Upvotes: 1
Views: 2336
Reputation: 12022
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];
});
Upvotes: 1