Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

node.js - Adding 'virtual' variables to a mongoose schema?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...