Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $scope.createProduct = function() {
- // validate the formData (using our exentions.js .filter) to make sure that something is there
- //if form is empty, nothing will happen
- if (!isEmptyObjectFilter($scope.formData)) {
- // call the create function from our service (returns a promise object)
- Emotions.create($scope.formData)
- // if successful creation, call our get function to get all the new emotions
- .success(function(data) {
- $scope.formData = {}; // clear the form so our user is ready to enter another
- $scope.products = data; // assign our new list of emotions
- })
- .error(function(data) {
- console.log('Error: ' + data);
- });
- }
- };
- } else if(typeof doc.position == "number") {
- console.log('yes, a number');
- // check if there is an existing document with the same position
- // use mongoose.model to fetch the model because the model is not compiled yet
- mongoose.model("Product").where({_id: {$ne: doc._id}, position: doc.position}).count( function (err, count) {
- // if there was an error, pass it to next()
- if(err)
- return next(err);
- // if there is a doc with the same position, execute an update to move down all the $gte docs
- if(count > 0) {
- // use mongoose.model to fetch the model because the model is not compiled yet
- mongoose.model("Product").update({position: {$gte: doc.position}}, {position: {$inc: 1}}, {multi: 1}, function(err, numAffected) {
- console.log(numAffected);
- // Call next() (with or without an error)
- next(err);
- });
- } else {
- // there are no docs that need to move down, so call next()
- next();
- }
- });
- var ProductSchema = mongoose.Schema({
- title : String,
- position: Number
- });
- // before validation starts, the number of Products is counted
- // afterwards, the position is set
- ProductSchema.pre("validate", function(next) {
- var doc = this;
- // if 'position' is not filled in, fill it in
- // not using !position because 0 might be a valid value
- if(typeof doc.position !== "number") {
- // count the number of Products *
- // use mongoose.model to fetch the model..because it's not compiled yet
- mongoose.model("Product").count(function(err, num) {
- // if there was an error, pass it to next()
- if(err)
- return next(err);
- // set the position, then call next();
- doc.position = num;
- return next();
- });
- } else {
- // there is no need to count or update positions, so call next()
- next();
- }
- });
- module.exports = mongoose.model('Product', ProductSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement