Search code examples
javascriptnode.jsmongodbmonk

MongoDB findAndModify not working with monk


I am trying to use findAndModify with the node.js mongodb module monk.This is the method that I am using,this throws a 500 error in my cmd:

  notesCollection.findAndModify({_id:_id},[],{_id:_id,title:title,content:content},{'new':true,'upsert':true},function(err,doc){
    if(err)
        console.error(err);
    else
    {
        console.log("Find and modify successfull");
        console.dir(doc);
    }   
});

I obtained the method signature here.I get an error that looks like this and is uninformative:

 POST /notes/edit/542bdec5712c0dc426d41342 500 86ms - 1.35kb

Solution

  • Monk implements methods that are more in line with the shell syntax for method signatures than what is provided by the node native driver. So in this case the "shell" documentation for .findAndModify() is more appropriate for here:

      notescollection.findAndModify(
          {
            "query": { "_id": id },
            "update": { "$set": { 
                "title": title,
                "content": content
            }},
            "options": { "new": true, "upsert": true }
          },
          function(err,doc) {
            if (err) throw err;
            console.log( doc );
          }
    );
    

    Also noting that you should be using the $set operator or posibly even the $setOnInsert operator where you only want fields applied when the document is created. When operators like this a re not applied then the "whole" document is replaced with whatever content you specify for the "update".

    You also don't need to supply the "_id" field in the update section, as even when an "upsert" occurs, anything present in the "query" portion of the statement is implied to be created in a new document.

    The monk documentation also hints at the correct syntax to use for the method signature.