Last active
December 19, 2015 02:58
-
-
Save jackboberg/5886317 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var ContactSchema = require('./contact'); | |
var UserSchema = new mongoose.Schema({ | |
email: {type: String}, | |
name: {type: String}, | |
//oauth: {}, | |
profile: {type: Object}, | |
contacts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Contact' }] | |
}); | |
UserSchema.set('toJSON', { | |
virtual:true, | |
getters: true, | |
transform: function(doc, ret, options){ | |
delete ret.__v; | |
delete ret._id; | |
} | |
}); | |
module.exports = UserSchema; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
exports.createContact = function(req, res, next) { | |
models.User.findById(req.params.id, function(err, user){ | |
if (err) { | |
return next(err); | |
} | |
models.Contact.create(req.body, function(err, contact){ | |
if (err) { | |
return next(err); | |
} | |
user.contacts.push(contact.id); | |
user.save(function(err){ | |
if (err) { | |
return next(err); | |
} | |
res.json(201, contact); | |
}); | |
}); | |
}); | |
}; | |
exports.addContact = function(req, res, next) { | |
var data = { $addToSet: { contacts: req.params.contactId } }; | |
models.User.findByIdAndUpdate(req.params.id, data, function(err, user){ | |
if (err) { | |
return next(err); | |
} | |
res.json(200, user); | |
}); | |
}; | |
exports.removeContact = function(req, res, next) { | |
var data = { $pull: { contacts: req.params.contactId } }; | |
models.User.findByIdAndUpdate(req.params.id, data, function(err, user){ | |
if (err) { | |
return next(err); | |
} | |
res.json(200, {success:true}); | |
}); | |
}; | |
// ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
app.post('/api/categories/:id/contacts', categoryApi.createContact); | |
app.put('/api/users/:id/contacts/:contactId', userApi.addContact); | |
app['delete']('/api/users/:id/contacts/:contactId', userApi.removeContact); | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment