Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong result type for updateOne #10042

Closed
SimonVillage opened this issue Mar 19, 2021 · 0 comments
Closed

Wrong result type for updateOne #10042

SimonVillage opened this issue Mar 19, 2021 · 0 comments
Labels
typescript Types or Types-test related issue / Pull Request
Milestone

Comments

@SimonVillage
Copy link
Contributor

SimonVillage commented Mar 19, 2021

Do you want to request a feature or report a bug?
bug

What is the current behavior?
I am using updateOne with upsert: true to update or create a document. I need to check if a document was created (upserted) or updated. I tried using res.nModified; but it returns 0 if the document was upserted OR not updated.

If the current behavior is a bug, please provide the steps to reproduce.
Referencing: https://masteringjs.io/tutorials/mongoose/upsert

const result = await MyModel.updateOne(
  { status: "completed" },
  { foo: "bar" },
  { upsert: true }
);

result will be:

{
  n: 1,
  nModified: 0,
  upserted: [ { index: 0, _id: 605455642dfbeba567704211 } ],
  ...
}

However result.upserted does not exist in types:
Property 'upserted' does not exist on type '{ ok: number; n: number; nModified: number; }'.

https://github.com/Automattic/mongoose/blob/master/index.d.ts#L857 is using https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/mongodb/index.d.ts#L2772 which has the following definition:

/** @see https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~updateWriteOpResult */
export interface UpdateWriteOpResult {
    result: { ok: number; n: number; nModified: number };
    connection: any;
    matchedCount: number;
    modifiedCount: number;
    upsertedCount: number;
    upsertedId: { _id: ObjectId };
}

What is the expected behavior?
I need to know if a document was updated or upserted. If nModified == 0 it could be that the document got upserted or not updated at all as it didn't had any changes.

I could use fineOneAndUpdate however, updatedExisting is always true even if the data did not change for an update.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
mongoose: 5.12.1
mongodb: 3.6.5
node: v14.15.4

@vkarpov15 vkarpov15 added this to the 5.12.2 milestone Mar 20, 2021
@vkarpov15 vkarpov15 added the typescript Types or Types-test related issue / Pull Request label Mar 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
typescript Types or Types-test related issue / Pull Request
Projects
None yet
Development

No branches or pull requests

2 participants