Reputation: 2805
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?
Upvotes: 4
Views: 1867
Reputation: 4054
You can not add extra property with mongoose model without specifying it in schema. if you want to save the added property you have to add this in schema level. otherwise use toobject()
method to transfer it in normal javascript object.
data = data.toObject();
data.any_property_name = required_value;
one thing you can not save this object in database. As it is a plain javascript object.
Upvotes: 0
Reputation: 311865
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;
Upvotes: 3