Search code examples
node.jsmongoosefindoneandupdate

Mongoose `findOneAndUpdate` returns `QueryWithHelpers` instead of result


I have the following invocation.

  static findOneAndUpdate(
    filter: FilterQuery<ISyncedOrder>,
    update: UpdateQuery<ISyncedOrder>
  ): Promise<ISyncedOrder> {
    return SyncedOrders.findOneAndUpdate(
      filter,
      update,
      {upsert: true}
    );
  }

According to documents, I should be getting a document. But, IDE shows an error of a type mismatch (screenshot below).

enter image description here

When I checked the node module, I see the following signature for the method findOneAndUpdate.

enter image description here

What am I missing? Looks like I am headed in a wrong direction.


Solution

  • The issue occurs because "Mongoose queries are not promises".

    They support just enough to be used as one (it's a "thenable"), but not enough to fool TypeScript into believing it's actually a promise.

    The Mongoose documentation also suggests how to get a real promise: by using Query.exec():

    return SyncedOrders.findOneAndUpdate(
      filter,
      update,
      {upsert: true}
    ).exec();