Mongoose: findOneAndUpdate using findAndModify

Created on 10 Jul 2016  路  3Comments  路  Source: Automattic/mongoose

Why is the findOneAndUpdate method using findAndModify under the hood instead of findOneAndUpdate?

I need to pass projection settings but it's not working because findAndModifiy doesn't take such parameters, and as such it's returning the entire document.

E.g.:

Product
      .findOneAndUpdate({
        _id: productId,
      }, {
        $push: {colors: data},
      }, {
        projection: {
          name: 1, 'colors.$': 1,
        },
        returnNewDocument: true,
      })

Most helpful comment

Yeah there's a little confusion there because every API wants to be it's own special snowflake :) Now that the mongodb driver added a findOneAndUpdate() function that has its own quirks, not quite sure yet with how to proceed on mongoose's fineOneAndUpdate()

All 3 comments

Because mongoose's findOneAndUpdate() long predates the existence of findOneAndUpdate() in the underlying mongodb driver, and the driver's findOneAndUpdate() is just a thin wrapper around findAndModify anyway. Also, the driver's findOneAndUpdate() has several quirky semantics, especially related to the new option and the difference between new and returnNewDocument, that are troublesome for mongoose.

Projections not working is a bit of a problem. Try using 'fields' instead of 'projection', because that's the name the underlying findAndModify function uses

Thanks for clarifying. Yes I noticed that there were some odd differences in naming, e.g. fields vs projection and new vs. returnNewDocument.

Yeah there's a little confusion there because every API wants to be it's own special snowflake :) Now that the mongodb driver added a findOneAndUpdate() function that has its own quirks, not quite sure yet with how to proceed on mongoose's fineOneAndUpdate()

Was this page helpful?
0 / 5 - 0 ratings