Skip to content

Instantly share code, notes, and snippets.

@jackboberg
Last active December 19, 2015 02:58
Show Gist options
  • Save jackboberg/5886317 to your computer and use it in GitHub Desktop.
Save jackboberg/5886317 to your computer and use it in GitHub Desktop.
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;
// ...
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});
});
};
// ...
// ...
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