Skip to content

Instantly share code, notes, and snippets.

@dxg
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dxg/9523421 to your computer and use it in GitHub Desktop.
Save dxg/9523421 to your computer and use it in GitHub Desktop.
orm.connect(config, function (error, db) {
//Declare Variables
var models = {};
//Settings
db.settings.set("properties.primary_key", "id");
db.settings.set("instance.cache", false);
db.settings.set("instance.autoSave", false);
db.settings.set("instance.autoFetch", false);
db.settings.set("instance.autoFetchLimit", 2);
//Define Models
models.users = db.define("users", {
name: String,
email: String
});
models.users.groups = db.define("users_group", {
name: String,
private: Boolean
}, {
hooks: {
beforeRemove: function () {
console.log("before remove");
},
afterRemove: function () {
console.log("after remove");
}
}
});
//Create Associations
models.users.groups.hasOne("owner", models.users);
models.users.groups.hasMany("users", models.users, {}, {
reverse: "groups",
autoFetch: true
});
//Sync Models
db.drop(function (err) {
if (err) throw new Error(err);
db.sync(function (err) {
if (err) throw new Error(err);
async.series([
//Populate Models
function (callback) {
models.users.create({
name: "Brian",
email: "brian@laborate.io"
}, function (err, user) {
models.users.groups.create({
name: "Friends",
private: true
}, function (err, group) {
user.addGroups(group, callback);
});
});
},
//Update Information
function (callback) {
models.users.get(1, function(err, user) {
if (err) throw new Error(err);
user.save({
name: "John Doe",
email: "john@doe.com"
}, function (err) {
if (err) throw new Error(err);
//Check If Group has User
models.users.groups.get(1, function(err, group) {
if (err) throw new Error(err);
group.hasUsers(user, function (err, result) {
console.log(err, result);
callback();
});
});
});
});
},
// Test remove
function (callback) {
models.users.groups.get(1, function (err, group) {
if (err) return callback(err);
group.remove(callback);
});
}
], function (err) {
console.log(err);
//End Program
process.exit(0);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment