node.js - Array Manipulation with Mongoose -


i have schema employee , team. when update employee can change team. want happen update employee team id , remove employee every other team in database. employee can in 1 team business rule enforcing.

these abridged schemas working with.

employee schema

var employeeschema = new schema({   id: {     type: string,     required: true,     unique: true   },   team: {     type: schema.types.objectid,     ref: 'team'   } }); 

team schema

var teamschema = new schema({   name: {     type: string,     required: true   },   members: [{     type: schema.types.objectid,     ref: 'employee'   }] }); 

what want happen when change employees team, want remove employee every teams list of members, update employee's team reference, , update new team's array of members.

current code

var empmongoid = req.params.id; team.update({   $pull: {     members: {       _id:empmongoid     }   } }, {   multi: true }, function (err, numberaffected, raw) {   console.log(err, numberaffected, raw);   callback(null); }) 

this nothing , log null, 0, undefined.

as mentioned in comment, might want change schema team not contain reference employees, leaving reference on employee. removes need programatically "update" teams keep user lists in sync or construct crazy convoluted update queries.

so, schema this:

var employeeschema = new schema({     id: {         type: string,         required: true,         unique: true     },     team: {         type: schema.types.objectid,         ref: 'team'     } }); mongoose.model('employee', employeeschema)  var teamschema = new schema({     name: {         type: string,         required: true     } });  teamschema.methods.getemployees = function (fn) {     return this.model('employee').find({ team: this._id }, fn) }  mongoose.model('team', teamschema) 

to use:

var team = ... //load team somehow team.getemployees(function (err, employees) {     //do list of employees }); 

the idea here schema enforces many-to-one relationship between employee , team. employee can part of 1 team definition in schema, team needs provide method search employees matching team id. team never directly holds references.

this more or less see in normal relational database well, same ideas can apply when using mongoose give "schema" non-relational schemaless database (which imo means should move database schema, mongodb cool in many ways queries , other stuff justify use in "schema'd" situation).


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -