Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Mongoose model without storing all properties

I'm building a CMS based on Node.js+Express+Mongoose. I want abstract layers for business and data access methods. So I have biz classes containing the methods with the calls to the database.

These calls are made using directly the Mongoose models, so my logical entities are Mongoose entities.

The problem is that some logical entity is not always identical to its database entity.

For example: I have a model called "Item" with its properties and these properties have to be stored into the database, that's just fine. Now, I need a new property, an array called "similar_items" that can, eventually, contain a list of other items but I don't want to store this property inside the database.

var itemSchema = new Schema({
    id: { type: Number, index: true },
    name: { type: String }
});

var item = mongoose.model('Item', itemSchema);    
var data = new Item();
/* do stuff....  */
data.similar_items = blahblah; //I can't set this property as it doesn't exists!

Is it possible to extend a Mongoose model with properties out of its schema? I know I can define virtual properties with getters and setters, but I still don't have a "place" to store my array.

Any idea? Should I separate my logical and Mongoose models?

like image 591
Darko Romanov Avatar asked Sep 15 '25 06:09

Darko Romanov


1 Answers

If you're done using data as a Mongoose instance at that point, call toObject() on it to convert it to a plain JS object that you can freely modify:

data = data.toObject();
data.similar_items = blahblah;
like image 123
JohnnyHK Avatar answered Sep 17 '25 20:09

JohnnyHK