view raw
Zlatko Zlatko - 9 months ago 52
Node.js Question

How to swap fields on docs with unique constraint in MongoDB/mongoose?

I have docs in series:

_id: ObjectId(),
position: 1,
name: 'This doc'
_id: ObjectId(),
position: 2
name: 'That doc'

field has a unique constraint. Also, I need them all ordered, from 1 to
with no holes.

How can I swap those things? If I put pos:1 to pos:2 and the other way around, I try to save, I get validation error on the first doc. Or when I try to save the whole series, it's even harder (ie. move doc from pos 7 to pos 2, which in turn moves all from 2-6 down by one).

What is a good strategy to do this with MongoDB? And, preferably applicable to Mongoose models or schemas?


Swap all the other fields than position.

var query = {$or:[{position: 1},{position: 2}]};
Schema.find(query, function(err, docs){
        if(key=='position') return;
        var temp = docs[0][key];
        docs[0][key] = docs[1][key];
        docs[1][key] = temp;