Skip to content

update/upsert: _id is generated even if you send a pre-generated _id the json object #39

Description

@ejbp

Consider this lines of code with an empty db file:

[...]

//I need to pre-generate the _id of this object and not use a auto-generated _id 
var obj = {
  "_id": "xxxxxxx",
  "name":  "test"
};

console.log("Before: ", obj);
db.records.update({ _id : "xxxxxxx" },  obj, {multi: false, upsert: true});
console.log("After: ", obj);

[...]

The output will be:

Before: { "_id": "xxxxxxx", "name":  "test"}
After: { "_id": "6aec8d48d5284def9c3c85428b506d95", "name":  "test"}

//being '6aec8d48d5284def9c3c85428b506d95' the new generated _id when it should be 'xxxxxxx'

After looking into the module code, I noticed that you don't verify if the _id already exists:

filename: collection.js

coltn.update = function(query, data, options) {
        var ret = {},
            collection = JSON.parse(util.readFromFile(this._f)); // update
        var records = util.finder(collection, query, true);
        if (records.length) {
            if (options && options.multi) {
                collection = util.updateFiltered(collection, query, data, true);
                ret.updated = records.length;
                ret.inserted = 0;
            } else {
                collection = util.updateFiltered(collection, query, data, false);
                ret.updated = 1;
                ret.inserted = 0;
            }
        } else {
            if (options && options.upsert) {
                //It would be nice if you verify if the _id exists and only create a new one if not 
                data._id = uuid.v4().replace(/-/g, ''); 
                collection.push(data);
                ret.updated = 0;
                ret.inserted = 1;
            } else {
                ret.updated = 0;
                ret.inserted = 0;
            }
        }
        util.writeToFile(this._f, collection);
        return ret;
    };

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions