Greeting all!
I defined a Mongoose schema as below and registered a model (InventoryItemModel). Is there a way to create a custom constructor function for the schema, so that when I instantiate an object from the model, the function will be called (for example, to load the object with value from database)?
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var InventoryItemSchema = new Schema({
Sku : String
, Quanity : Number
, Description : String
, Carted : []
, CreatedDate : {type : Date, default : Date.now}
, ModifiedDate : {type : Date, default : Date.now}
});
mongoose.model('InventoryItem', InventoryItemSchema);
var item = new InventoryItem();
Can I add some custom constructor function so that the item will be populated from database upon instantiation?
Let's take a look at an example of a basic schema type: a 1-byte integer. To create a new schema type, you need to inherit from mongoose.SchemaType and add the corresponding property to mongoose.Schema.Types. The one method you need to implement is the cast () method.
New in Mongoose 4.4.0: Mongoose supports custom types. Before you reach for a custom type, however, know that a custom type is overkill for most use cases. You can do most basic tasks with custom getters/setters, virtuals, and single embedded docs. Let's take a look at an example of a basic schema type: a 1-byte integer.
Important: the actual interaction with the data happens with the Model that you obtain through mongoose.model or db.model. That's the object that you can instantiate or that you can call .find (), .findOne (), etc upon.
If you want to add more keys later, Schema#add provides the same functionality. Your schema is constructed by passing all the JavaScript natives that you know (String, Number, Date, Buffer) as well as others exclusive to MongoDb (for example Schema.ObjectId ).
Depending on the direction you want to take, you could:
1) Use Hooks
Hooks are automatically triggered when models init, validate, save, and remove. This is the 'inside-out' solution. You can check out the docs here:
2) Write a static creation function for your schema.
Statics live on your model object and can be used to replace functionality like creating a new model. If you have extra logic for your create
step, you can write it yourself in a static function. This is the 'outside-in' solution:
Here's an implementation of option #2 from @hunterloftis
's answer.
2) Write a static creation function for your schema.
someSchema.statics.addItem = function addItem(item, callback){
//Do stuff (parse item)
(new this(parsedItem)).save(callback);
}
When you want to create a new model from someSchema, instead of
var item = new ItemModel(itemObj);
item.save(function (err, model) { /* etc */ });
do this
ItemModel.addItem(itemObj, function (err, model) { /* etc */ });
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