javascript - Update a value for existing documents with Mongoose? -
i have document field 'position', used sorting results via angular loop on frontend.
right now, schema accurately auto-incrementing new documents lack 'position', , storing new documents have form-field-entered position.
when inserting item existing 'position' value, want move every record down. wrote javascript logic this, doesn't hit else if..
// load mongoose since need define schema , model var mongoose = require('mongoose'); var itemschema = mongoose.schema({ title : string, position: number }); // before validation starts, number of items counted..afterwards, position set itemschema.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 items * // use mongoose.model fetch model because model not compiled yet mongoose.model("item").count(function(err, num) { // if there error, pass next() if(err) return next(err); // set position, call next(); doc.position = num; return next(); }); } else if(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("item").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("item").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(); } }); } else { // there no need count or update positions, call next() next(); } }); module.exports = mongoose.model('item', itemschema);
Comments
Post a Comment