Virtual properties

Virtual properties are exactly what they sound like--fake properties that don't actually exist in your MongoDB documents, but that you can fake by combining other, real properties. The most obvious example of a virtual property would be a field for fullname, when only firstname and lastname are actual fields in the MongoDB collection. For fullname, you simply want to say, return the model's first and last name combined as a single string and label it as fullname:

// assuming the Account schema has firstname and lastname defined: 

Account.virtual('fullname')
.get(function() {
return this.firstname + ' ' + this.lastname;
})
.set(function(fullname) {
var parts = fullname.split(' ');
this.firstname = parts[0];
this.lastname = parts[1];
});

We call the .get() and .set() functions. It's not required to provide both, although it's fairly common.

In this example, our get() function simply performs basic string concatenation and returns a new value. Our .set() function performs the reverse splitting of a string on a space and then assigning the model's firstname and lastname field values with each result. You can see that the .set() implementation is a little flaky if someone attempts to set a model's fullname with a value of, say, Dr. Kenneth Noisewater.

It's important to note that virtual properties are not persisted to MongoDB, since they are not real fields in the document or collection.

There's a lot more you can do with Mongoose, and we only just barely scratched the surface. Fortunately, it has a fairly in-depth guide that you can refer to at the following link: http://mongoosejs.com/docs/guide.html.

Definitely spend some time reviewing the Mongoose documentation so that you are familiar with all of the powerful tools and options available.

That concludes our introduction to Mongoose's models, schemas, and validation. Next up, let's dive back into our main application and write the schemas and models that we will be using to replace our existing sample ViewModels and for connecting with Mongoose.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.233