Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findOneAndUpdate throw "Retryable writes are not supported" error when working with aws Documentdb

I have a schema as follows:

var answerSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    required: true
  }
)
mongoose.model("Answer", answerSchema)

and in another file I have:

var Answer = mongoose.model("Answer")
router.put("/test", function (req, res){
  const query = { _id: "5fe656077ddb2a4e1a91d808"}
  const update = { username: 'test' }
  const options = {
    new: true,
    upsert: true,
    setDefaultsOnInsert: true
  }
  
  Answer.findOneAndUpdate(query, update, options, function(error, doc) {
      if(error){
        res.send(error.message)
      }
      else{
        res.send('successfully saved.')
      }
    })
})

Currently in the mongo shell, I can run db.answers.find().pretty() and it gives me:

{
        "_id" : ObjectId("5fe656077ddb2a4e1a91d808"),
        "username" : "aaaa",
        "__v" : 0
}

However, when I use POSTMAN to access the "/test" URL, I get an error "Retryable writes are not supported". I know documentdb doesn't support retryable writes, but how does this FindOneAndUpdate require retryable writes? I also tried using set() and save() with findOne(), and the findOne() works fine, but the set() throws the same error. Did I miss something here?

like image 388
Elena Avatar asked Dec 26 '20 03:12

Elena


1 Answers

Retryable Writes are to handle cases where there is a network error during a write operation. You'd get this error for any of the write operations listed here, including save and findOneAndUpdate as you've experienced yourself.

The DocumentDB documentation of its functional differences with MongoDB includes a section on retryable writes, where it recommends setting retryWrites=false in the connection string to avoid these types of errors:

Starting with MongoDB 4.2 compatible drivers, retryable writes is enabled by default. However, Amazon DocumentDB does not currently support retryable writes. The functional difference will manifest itself in an error message similar to the following.

{"ok":0,"errmsg":"Unrecognized field: 'txnNumber'","code":9,"name":"MongoError"} 

Retryable writes can be disabled via the connection string (for example, MongoClient("mongodb://my.mongodb.cluster/db?retryWrites=false")) or the MongoClient constructor’s keyword argument (for example, MongoClient("mongodb://my.mongodb.cluster/db", retryWrites=False)).

like image 147
Montgomery Watts Avatar answered Nov 11 '22 22:11

Montgomery Watts