Search code examples
node.jsmongodbmonk

MongoDB, Monk, findAndModify not upserting


I have this function in a node project that is supposed to update or create a new entry based on whether the slug matches. It updates perfectly so the response being returned is correct but it won't insert a new item and I'm not sure what I've missed.

MongoDB version 3.0.4 (installed via Homebrew) Mac OSX Yosemite MongoDB Node package 2.0.39 Monk 1.0.1

collection.findAndModify({
      "query": { "slug": pluginslug },
      "update":
        {
            "slug"            : pluginslug,
            "name"            : response.data.name,
            "current_version" : response.data.version,
            "description"     : response.data.short_description,
            "change_log"      : response.data.sections.changelog,
            "updated"         : response.data.last_updated,
            "tested"          : response.data.tested
        },
      "upsert" :true,
      "new" : true
      }, function (err, doc) {
        if (err) {
          res.send("There was a problem adding the information to the database.");
        }
        else {
          console.log(doc)
          res.redirect("plugins/new");
        }
    });

Am I missing something really obvious here?


Solution

  • I've found the correct answer here: Issue with a simple mongo/monk findAndModify query

    The solution is to provide the options as an own object (it is not well documented by the monk docs):

    db.test.findAndModify(
    {
      "query": { "slug": "1234512345" },
      "update":
        {
            "$set": 
            {
                "slug"            : "1234512345",
                "name"            : "response.data.name",
                "current_version" : "response.data.version",
                "description"     : "response.data.short_description",
                "change_log"      : "response.data.sections.changelog",
                "updated"         : "response.data.last_updated",
                "tested"          : "response.data.teste"
            }
        }
    },
    {
      "upsert" :true,
      "new" : true
    }, 
    function (err, doc) {
        if (err) {
            console.log(err);
        }
        else {
          console.log(doc);
        }
    });