moodle

Model module for node for use with both mongodb and mysql.

moodle

$ npm install moodle
    
    var db    = require('your-mongo-instance');
    var Model = require('moodle');
    
    var User = new Model('User');
    
    User.storage('mongodb')
        .connect(
            function() { 
                // Return your mongo instance with selected collection 
                return db.users 
            }
        );
 
    /**
     * Define attributes
     */
    User.attr('_id', 'ObjectId');
    
    User.attr('username', 'String')
        .required();
    
    User.attr('permissions', 'Object');
    
    User.attr('password', 'String')
        .required();
    
    User.attr('last_login', 'Date')
        .default(null);
    
    User.attr('status', 'Bool')
        .default(true)
        .required();
    
    modules.export = User;
    
    var User = require('./models/user');
 
    /**
     * Save new
     */
    var user = new User();
    
    user.owner("51223c75bb64ba8d60000000");
    user.username("root");
    user.password("secret");
    user.permissions({
        wheel: true
    });
 
    user.save(function(err) {
        if (err) throw err;
        
        user._id(); // return the generated _id 
        // _id 
        
        console.log("saved!");
    });
 
    /**
     * Update model
     */
    User.findOne({_id: "51519576d2381d38df000003"}, function(erruser) {
        if (err) throw err;
        
        user.last_login(new Date());
        user.save(function(err) {
            if (err) throw err;
        });
    });
 
    /**
     * Find multiple
     */
    User.find({status:true}, function(errusers) {
    
        for (var user in users) {
            if (user instanceof User)
                // true 
        
        }
    
    });
  • String
  • Integer
  • Bool
  • Enum
  • Id
  • ObjectId
  • Object
  • Array
  • Date

Set an alias name for this attribute. It will be used for the error messages.

Returns the Attribute object for chaining.

Set this attribute as requirement. If a field is not required and not undefined, it will be validated. Otherwise, if it's required, it will be validated in every case.

Returns the Attribute object for chaining.

Add your own function to validate a field. This function is called with two parameters, the current attribute instance and the value. Errors have to be pushed to self.errors.

Example:

function(selfv) {
    if (!instanceof Array) {
        self.errors.push("Not a valid array: "+v);
    }
}

Returns the Attribute object for chaining.

Set the default value of this attribute. If a value is undefined, the default value is used.

Returns the Attribute object for chaining.

Adds a possible option to this attribute. Only added options were validated.

Returns the Attribute object for chaining.