mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Temporary (virtual) properties on model instance

Open wclr opened this issue 10 years ago • 29 comments

Sometimes I need to have on a model instance some temporaty property that is not in DB but for example I want to send to the client.

The scenario:

say I a have a Parent Model and Child model, I store them in separeate collections and only Child model has reference to it's parent

Parent.findOne({..}, function(err, parent){
    Child.find({parent: parent.id}, function(){err, children}{
        // now I want to send to the client parent instance with children as nested array
          parent.children = children
          res.send(parent)
    })
})

the problem is that parent.children = children won't work if children property is not defined on Parent schema. But its only temporary property and should not be saved to DB, it is not reasonable (and just incorrect) to define it on Parent schema.

The workaround I found is to add the followin virtual peroperty to Parent model:

parentSchema.virtual('children').get(function(){
    return this.__children
}).set(function(val){
    this.__children = val
})

I thought maybe something like that could work for such proerties:

// that would allow setting ```children``` but do not store it in DB
parentSchema.virtual('children') 

What do you think?

wclr avatar Feb 03 '15 10:02 wclr