Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 'virtual' variables to a mongoose schema?

Tags:

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?

like image 723
fusio Avatar asked Aug 14 '13 18:08

fusio


People also ask

What is virtual in Mongoose schema?

In Mongoose, a virtual is a property that is not stored in MongoDB. Virtuals are typically used for computed properties on documents. Your First Virtual.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.

Can Mongoose schema be changed?

There's nothing built into Mongoose regarding migrating existing documents to comply with a schema change. You need to do that in your own code, as needed.

What does .save do Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.


1 Answers

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

like image 150
gustavohenke Avatar answered Sep 20 '22 18:09

gustavohenke