dexie-mongoify icon indicating copy to clipboard operation
dexie-mongoify copied to clipboard

table.update() bugs

Open nevf opened this issue 8 years ago • 2 comments

@YurySolovyov I have found two problems with table.update() which I don't think are new.

  • Given table`.update( { 'panel': panel }, { 'show': show }, { upsert: true } ) the value { 'show': show } is not inserted (upserted). This happens when the update spec is a plain ``{ key: value }```. ie. It doesn't use $set etc. My fix is as follows:

Update createObjectForUpsert()

var createObjectForUpsert = function(query, update) {
    ......

    // If no Upsert operators were spec'd we use update as is. ie. i.e. update contains only field and value pairs. NF 2/01/2017
    // ref: https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-parameter
    if ( Object.getOwnPropertyNames( objectFromUpdate ).length === 0 )
        objectFromUpdate = update;

    return assign(objectFromQuery, objectFromUpdate);
};
  • Given table`.update( { 'panel': panel }, { 'show': show }, { upsert: true } ) the value { 'show': show } is not set if it doesn't already exist. ie. The panel object exists, but the show property doesn't. My fix for this is:
var createPlainPropertyUpdater = function(update, objectKeys) {
    var keys = objectKeys || Object.keys(update);
    return function(item) {
        // Replace entire document.
        // ref: https://docs.mongodb.com/manual/reference/method/db.collection.update/#example-update-replace-fields
        keys.forEach(function(key) {
            // if (has(item, key)) {     // this prevents plain update with values that don't already exist from working. ex. existing doc { a: "1" } -> update { b: "2" } NF 2/01/2017
                item[key] = update[key];
            // }
	        // TODO: item[ key ] which aren't present in update[] need to be removed. Can't be done here as we only have the update spec. Maybe do t in createPlainModifier(). NF 2/01/2017
        });
    };
};

Note that according to the MongoDB docs for collection.update() if no update modifiers are specified the entire document is replaced. At present this is not the case as per my TODO comment above.

I have not exhaustively tested these two fixes, which may possibly break other scenarios so please have a close look at them.

Neville

nevf avatar Jan 02 '17 00:01 nevf

@nevf did you tried running

npm t

with your patches? I'm quite busy ATM, but I'm ok with landing good enough PR with tests passing and/or new ones added :)

YurySolovyov avatar Jan 02 '17 18:01 YurySolovyov

@YurySolovyov No problem. Leave it with me.

nevf avatar Jan 03 '17 06:01 nevf