BadVolt
BadVolt

Reputation: 637

New document from mongoose method

I want to extend model with new method 'create'. It will check requirements for document creation, create additional documents and so on. Usually I call

var user = new User({});

But how can I create document from mongoose method itself? I.e.

User.methods.create = function(userObject,callback){
    //some checks
    var doc = ???;
    doc.save(function(err){
       if(err) return callback(err);
       //saving done
       callback(null,doc);
    });
}

UPD:

Thx to @chridam's answer my final code now looks like this:

User.statics.create = function(userObject,callback){
    //some checks
    var doc = this.model('User')(userObject);
    doc.save(function(err){
       if(err) return callback(err);
       //saving done
       callback(null,doc);
    });
}

Upvotes: 2

Views: 767

Answers (2)

chridam
chridam

Reputation: 103335

Statics will allow for defining functions that exist directly on your Model, so instead of an instance model (like you have tried), define a static method on the User class. Example:

var userSchema = new Schema({ firstname: String, lastname: String });

// assign a function to the "statics" object of our userSchema
userSchema.statics.create = function (userObject) {
    console.log('Creating user');
    // use Function.prototype.call() to call the Model.create() function with the model you need
    return mongoose.Model.create.call(this.model('User'), userObject);
};

Upvotes: 4

richardnixonthethird
richardnixonthethird

Reputation: 345

I know this is not answering your question exactly, but it may be what you are looking for.

check out the mongoose middleware http://mongoosejs.com/docs/middleware.html

There is a pre-save hook where you can do some validation and other things such as document creation.

Upvotes: 0

Related Questions