javascript - Increment field on all records in Mongo? -
the error being thrown in angular itemcontroller, error: typeerror: path must string
$scope.createproduct = function() { // validate formdata (using our exentions.js .filter) make sure there //if form empty, nothing happen if (!isemptyobjectfilter($scope.formdata)) { // call create function our service (returns promise object) emotions.create($scope.formdata) // if successful creation, call our function new emotions .success(function(data) { $scope.formdata = {}; // clear form our user ready enter $scope.products = data; // assign our new list of emotions }) .error(function(data) { console.log('error: ' + data); }); } };
adding else if, moving every record down when new position matches existing position, leads 500 internal server error..
} else if(typeof doc.position == "number") { console.log('yes, number'); // check if there existing document same position // use mongoose.model fetch model because model not compiled yet mongoose.model("product").where({_id: {$ne: doc._id}, position: doc.position}).count( function (err, count) { // if there error, pass next() if(err) return next(err); // if there doc same position, execute update move down $gte docs if(count > 0) { // use mongoose.model fetch model because model 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 error) next(err); }); } else { // there no docs need move down, call next() next(); } });
i have field 'position' on mongoose doc, sorting results via frontend angular loop.
var productschema = mongoose.schema({ title : string, position: number });
the schema auto-incrementing 'if' statement, new documents without 'position' entered..
// before validation starts, number of products counted // afterwards, position set productschema.pre("validate", function(next) { var doc = this; // if 'position' not filled in, fill in // not using !position because 0 might valid value if(typeof doc.position !== "number") { // count number of products * // use mongoose.model fetch model..because it's not compiled yet mongoose.model("product").count(function(err, num) { // if there error, pass next() if(err) return next(err); // set position, call next(); doc.position = num; return next(); });
..and schema otherwise storing doc because of 'else' statement, new documents manually-entered form-field 'position'.
} else { // there no need count or update positions, call next() next(); } }); module.exports = mongoose.model('product', productschema);
frontend: input type="number" class="form-control" placeholder="0" ng-model="formdata.position"
Comments
Post a Comment