Skip to content

Commit

Permalink
fix bug in implicit creation of arrays on set
Browse files Browse the repository at this point in the history
  • Loading branch information
nateps committed Aug 8, 2012
1 parent 1578970 commit b3a90a2
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var EventEmitter = require('events').EventEmitter
, createQueryCtor = require('./query')
, util = require('./util')
, fixId = util.fixId
, lookup

, DISCONNECTED = 1
, CONNECTING = 2
Expand All @@ -14,6 +15,7 @@ var EventEmitter = require('events').EventEmitter
exports = module.exports = plugin;

function plugin (racer) {
lookup = racer.util.path.lookup
DbMongo.prototype.Query = createQueryCtor(racer);
racer.registerAdapter('db', 'Mongo', DbMongo);
}
Expand Down Expand Up @@ -183,7 +185,7 @@ DbMongo.prototype.setupRoutes = function setupRoutes (store) {

function createCb (ver, done) {
return function findAndModifyCb (err, origDoc) {
if(err) return done(err);
if (err) return done(err);
adapter.setVersion(ver);
if (origDoc && origDoc._id) {
origDoc.id = maybeCastId.fromDb(origDoc._id);
Expand All @@ -193,7 +195,7 @@ DbMongo.prototype.setupRoutes = function setupRoutes (store) {
};
}

store.route('set', '*.*.*', -1000, function setCb (collection, _id, relPath, val, ver, done, next) {
function setCb (collection, _id, relPath, val, ver, done, next) {
if (relPath === 'id') relPath = '_id';
var setTo = {};
setTo[relPath] = val;
Expand All @@ -202,14 +204,35 @@ DbMongo.prototype.setupRoutes = function setupRoutes (store) {
if (collection !== 'sessions') {
_id = maybeCastId.toDb(_id);
}

// Patch-up implicit creation of arrays in a path, since Mongo
// will create an object if not already an array
var cb = /\.[0-9]+(?=\.|$)/.test(relPath) ?
function (err, origDoc) {
if (err) return done(err);
var re = /\.[0-9]+(?=\.|$)/g
, root;
while (match = re.exec(relPath)) {
root = relPath.slice(0, match.index);
if (lookup(root, origDoc) == null) {
setCb(collection, _id, root, [], ver, function() {
setCb(collection, _id, relPath, val, ver, done, next);
});
return;
}
}
createCb(ver, done)(err, origDoc);
} : createCb(ver, done);

adapter.findAndModify(collection
, {_id: _id} // Conditions
, [] // Empty sort
, op // Modification
, {upsert: true} // If not found, insert the object represented by op
, createCb(ver, done)
, cb
);
});
}
store.route('set', '*.*.*', -1000, setCb);

store.route('set', '*.*', -1000, function (collection, id, doc, ver, done, next) {
var findAndModifyCb = createCb(ver, done);
Expand Down

0 comments on commit b3a90a2

Please sign in to comment.