Permalink
Browse files

preserve MongooseArray#sort changes

closes #752
  • Loading branch information...
1 parent e38412b commit 4ef28d59d103ac2759814263f6d9cd761a937b69 @aheckmann aheckmann committed Jul 13, 2012
Showing with 62 additions and 0 deletions.
  1. +12 −0 lib/types/array.js
  2. +50 −0 test/types.array.test.js
View
12 lib/types/array.js
@@ -377,6 +377,18 @@ MongooseArray.prototype.unshift = function () {
};
/**
+ * sort
+ *
+ * @api public
+ */
+
+MongooseArray.prototype.sort = function () {
+ var ret = [].sort.apply(this, arguments);
+ this._registerAtomic('$set', this);
+ return ret;
+}
+
+/**
* Adds values to the array if not already present.
* @api public
*/
View
50 test/types.array.test.js
@@ -778,6 +778,56 @@ describe('types array', function(){
});
})
+ describe('sort()', function(){
+ it('order should be saved', function(done){
+ var db = start();
+ var M = db.model('ArraySortOrder', new Schema({ x: [Number] }));
+ var m = new M({ x: [1,4,3,2] });
+ m.save(function (err) {
+ assert.ifError(err);
+ M.findById(m, function (err, m) {
+ assert.ifError(err);
+
+ assert.equal(1, m.x[0]);
+ assert.equal(4, m.x[1]);
+ assert.equal(3, m.x[2]);
+ assert.equal(2, m.x[3]);
+
+ m.x.sort();
+
+ m.save(function (err) {
+ assert.ifError(err);
+ M.findById(m, function (err, m) {
+ assert.ifError(err);
+
+ assert.equal(1, m.x[0]);
+ assert.equal(2, m.x[1]);
+ assert.equal(3, m.x[2]);
+ assert.equal(4, m.x[3]);
+
+ m.x.sort(function(a,b){
+ return b > a;
+ })
+
+ m.save(function (err) {
+ assert.ifError(err);
+ M.findById(m, function (err, m) {
+ assert.ifError(err);
+
+ assert.equal(4, m.x[0]);
+ assert.equal(3, m.x[1]);
+ assert.equal(2, m.x[2]);
+ assert.equal(1, m.x[3]);
+ done();
+ })
+ })
+ })
+ })
+ });
+ })
+ })
+ })
+
describe('setting a doc array', function(){
it('should adjust path positions', function(done){
var db = start();

0 comments on commit 4ef28d5

Please sign in to comment.