Last active
August 26, 2015 03:04
-
-
Save johnbahamon/f2fec1394697baa636f8 to your computer and use it in GitHub Desktop.
Category Hierarchy
This file contains hidden or 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
apiRouter.route('/categories') | |
.get(function (req, res) { | |
Categories.find(function (err, categories) { | |
if (err) res.send(err); | |
// return categories | |
res.json(categories); | |
}); | |
}) | |
// create a category (accessed at POST http://localhost:8080/api/categories) | |
.post(function (req, res) { | |
Categories.findOne({'_id': req.body.parent}, 'ancestors', function (err, parents) { | |
// create a new instance of the categories model | |
var categories = new Categories(); | |
categories.slug = req.body.slug; | |
categories.name = req.body.name; | |
if (req.body.parent == undefined) { | |
categories.save(function (err) { | |
if (err) { | |
// duplicate entry | |
if (err.code == 11000) | |
return res.json({ success: false, message: 'A category with that name already exists.'}); | |
else | |
return res.send(err); | |
} | |
res.json({ message: 'Category created!' }); | |
}); | |
} else { | |
categories.parent = req.body.parent; | |
if (parents.ancestors.length == 0) { | |
categories.ancestors = req.body.parent; | |
categories.save(function (err) { | |
if (err) { | |
// duplicate entry | |
if (err.code == 11000) | |
return res.json({ success: false, message: 'A category with that name already exists. '}); | |
else | |
return res.send(err); | |
} | |
res.json({ message: 'Category created!' }); | |
}); | |
} else{ | |
parents.ancestors.push(req.body.parent); | |
categories.ancestors = parents.ancestors; | |
categories.save(function (err) { | |
if (err) { | |
// duplicate entry | |
if (err.code == 11000) | |
return res.json({ success: false, message: 'A category with that name already exists. '}); | |
else | |
return res.send(err); | |
} | |
res.json({ message: 'Category created!' }); | |
}); | |
} | |
}; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment