Quinn Keaveney
Quinn Keaveney

Reputation: 1574

How do I get keystoneJS to run a function once a specific model has been updated?

I want to run a function once I have a new or updated item in a specific KeystoneJS model. How do I do that? Would I add an event... is there an event already? Do I add it in the model or elsewhere?

Upvotes: 1

Views: 937

Answers (2)

Creynders
Creynders

Reputation: 4583

You can use mongoose middleware as with any non-keystone project. A keystone lists schema can be accessed with .schema, e.g.

var keystone = require('keystone');
var Types = keystone.Field.Types;


var User = new keystone.List('User');

User.add({
    name: { type: Types.Name, required: true, index: true },
    email: { type: Types.Email, initial: true, required: true, index: true },
});

//do stuff BEFORE the user document is fully saved to the DB
User.schema.pre('save', function(next){
    console.log('SAVING USER:', this);
    next();
});
//do stuff AFTER the user document has been saved to the DB
User.schema.post('save', function(user){
    console.log('USER WAS SAVED:', user);
});


User.defaultColumns = 'name, email';
User.register();

Take a look at mongoose middleware, since some restrictions apply, for instance when doing mass updates the middleware will not run, this is by design in mongoose and has nothing to do with keystone.

Upvotes: 2

enRaiser
enRaiser

Reputation: 2636

KEystoneJS uses mongoose.

When you add new model, the CRUD(change,Replace,Update, Delete) happens naturally in Admin side(http:///keystone

However for non-admin side You need to make Routes, and in routes views you can use mongoose API to do so.

any change in in keystoneJS, can be made working just by restarting the server (nam start)

Upvotes: 0

Related Questions