9

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?

Elena
  • 93
  • 1
  • 1
  • 4
  • I found a similar question [here](https://stackoverflow.com/questions/50283081/mongodb-error-cannot-use-retryable-writes-with-limit-0), does your connection string contain `?retryWrites=true`? – Montgomery Watts Dec 26 '20 at 05:31
  • 1
    yes, but documentdb itself doesn't support retryable writes, so this doesn't work. Why does updating need retryable writes though? – Elena Dec 26 '20 at 21:23

1 Answers1

28

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)).

Montgomery Watts
  • 3,806
  • 2
  • 10
  • 24