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

The function .transform of .findOne gets called twice #14236

Closed
2 tasks done
stantanasi opened this issue Jan 6, 2024 · 0 comments
Closed
2 tasks done

The function .transform of .findOne gets called twice #14236

stantanasi opened this issue Jan 6, 2024 · 0 comments
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@stantanasi
Copy link

stantanasi commented Jan 6, 2024

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.0.3

Node.js version

20.10.0

MongoDB server version

5.0.4

Typescript version (if applicable)

5.3.3

Description

The .transform function when using .findOne is executed twice instead of once.

Steps to Reproduce

const UserSchema = new Schema({
  name: String,
})

const User = model('User', UserSchema)

const user = new User({
  name: "John Doe"
})

await user.save()

let i = 1
console.log("-------- FIND ONE --------")
await User.findById(user._id)
  .transform((doc) => {
    console.log("Transform executed:", i++)
    return doc
  })
/**
 * -------- FIND ONE --------
 * Transform executed: 1
 * Transform executed: 2 // <- WRONG
 */

i = 1
console.log("-------- FIND --------")
await User.find()
  .transform((doc) => {
    console.log("Transform executed:", i++)
    return doc
  })
/**
 * -------- FIND --------
 * Transform executed: 1
 */

Expected Behavior

The .transform function should be executed only once.

Example of error occured:

const name = await User.findById(user._id)
  .transform((doc) => {
    return doc!.name
  })
console.log(name) // Should display user's name but it's undefined (= user.name.name)
@vkarpov15 vkarpov15 added this to the 8.0.4 milestone Jan 6, 2024
@vkarpov15 vkarpov15 added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Jan 6, 2024
vkarpov15 added a commit that referenced this issue Jan 6, 2024
vkarpov15 added a commit that referenced this issue Jan 7, 2024
avoid double-calling query transform() with findOne()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

No branches or pull requests

2 participants