user10696040
user10696040

Reputation: 79

Mogoose findOneAndUpdate Callback is not a function

I am recieving an error when I try to update an existing document. I have looked at other solutions but I am unable to solve my issue.

Error:

MongooseError: Callback must be a function, got [object Object]

Code:

formSchemas.findOneAndUpdate({'email':email, 'condition1': condition1, 'condition2': condition2},
        { $set: { "v1": v1, "v2": v2,
          "v3": v3, "v4": v4,
          "v5": v5 }},
          {new: true},
          {returnOriginal:false},
           function(err, doc){
            if (err){
              console.log(err);
              return res.send({
                success: false,
                message: 'Error somewhere!'
              });
            } 
            return res.send({
              success: true,
              message: 'Updated!'
            });
        }); // findoneandupdate

Where v1, v2.. are the things I want to update in mongo and the names of the fields in mongo. Not sure why the callback is not a function.

Upvotes: 3

Views: 4820

Answers (1)

Estus Flask
Estus Flask

Reputation: 222503

findOneAndUpdate expects up to 4 arguments, all of them are optional:

[conditions] «Object»

[update] «Object»

[options] «Object» optional see Query.prototype.setOptions()

[options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean().

[callback] «Function»

While 5 arguments was provided, {returnOriginal:false} is the one that isn't needed and was confused with callback argument.

returnOriginal isn't a valid option in current Mongoose versions. In case new document should be returned instead of original, this is the case for new option, which is already used:

new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

It should be:

formSchemas.findOneAndUpdate({'email':email, 'condition1': condition1, 'condition2': condition2},
        { $set: { "v1": v1, "v2": v2,
          "v3": v3, "v4": v4,
          "v5": v5 }},
          {new: true},
           function(err, doc){
           ...
           }
);

Callback API is obsolete, Mongoose is well-suited to work with promises.

Upvotes: 4

Related Questions