Adding 'virtual' variables to a mongoose schema?

mongoose, node.js

Solution

This is perfectly possible in mongoose. Check this example, taken from their documentation:

var personSchema = new Schema({
  name: {
    first: String,
    last: String
  }
});

personSchema.virtual('name.full').get(function () {
  return this.name.first + ' ' + this.name.last;
});
console.log('%s is insane', bad.name.full); // Walter White is insane

In the above example, the property would not have a setter. To have a setter for this virtual, do this:

personSchema.virtual('name.full').get(function () {
  return this.name.full;
}).set(function(name) {
  var split = name.split(' ');
  this.name.first = split[0];
  this.name.last = split[1];
});

Documentation

Problem

I have the following document schema: ``` var pageSchema = new Schema({ name: String , desc: String , url: String }) ``` Now, in my application I would like to also have the html source of the page inside the object, but I do not want to store it in the db. Should I create a "local" enhanced object which has a reference to the db document? ``` function Page (docModel, html) { this._docModel = docModel this._html = html } ``` Is there a way to use the document model directly by adding a "virtual" field?

Original source