Skip to content

Instantly share code, notes, and snippets.

@particlebanana
Created March 29, 2015 21:23
Show Gist options
  • Save particlebanana/f199ecf93af91af46b10 to your computer and use it in GitHub Desktop.
Save particlebanana/f199ecf93af91af46b10 to your computer and use it in GitHub Desktop.
Mongo association examples
/**
* User.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
name: 'string',
groups: {
collection: 'workgroup',
via: 'members',
dominant: true
}
}
};
/**
* Workgroup.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
name: 'string',
members: {
collection: 'user',
via: 'groups'
},
}
};
/**
* WorkgroupController
*
* @description :: Server-side logic for managing workgroups
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
link: function(req, res) {
var tasks = [];
/**
* CREATE
*/
//create main user
tasks.push(function(cb){
User.create({"id" : "54e8cc422acb5e5b03d5c845","firstName" : "Kitten","lastName" : "Handsome"}).exec(cb);
});
//create fellow users
tasks.push(function(cb){
User.create([
{"id" : "54ee20a72acb5e5b03d5c8a0","firstName" : "User2","lastName" : "User2"},
{"id" : "54ee20a72acb5e5b03d5c8a1","firstName" : "User3","lastName" : "User3"},
{"id" : "54ee20a72acb5e5b03d5c8a2","firstName" : "User4","lastName" : "User4"}
]).exec(cb);
});
//create workgroup
tasks.push(function(cb){
Workgroup.create([{"id" : "54ee23b82acb5e5b03d5c8a3", "fullName":"Kittens club"}]).exec(cb);
});
/**
* UPDATE ASSOCIATIONS
*/
//update workgroup with members
tasks.push(function(cb){
Workgroup.update({id:"54ee23b82acb5e5b03d5c8a3"},{
members:["54e8cc422acb5e5b03d5c845","54ee20a72acb5e5b03d5c8a0","54ee20a72acb5e5b03d5c8a1","54ee20a72acb5e5b03d5c8a2"]
}).exec(cb);
});
async.series(tasks, function(){
Workgroup.findOne("54ee23b82acb5e5b03d5c8a3").exec(function(err, group){
res.json(group);
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment