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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With