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

Clone Query ignores hooks #12365

Closed
2 tasks done
Naeoth opened this issue Aug 31, 2022 · 1 comment · Fixed by #12418
Closed
2 tasks done

Clone Query ignores hooks #12365

Naeoth opened this issue Aug 31, 2022 · 1 comment · Fixed by #12418
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@Naeoth
Copy link

Naeoth commented Aug 31, 2022

Prerequisites

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

Mongoose version

6.5.0

Node.js version

16.15.0

MongoDB server version

5.0

Description

The clone function from a Query doesn't trigger the hooks defined in its schema.

It may leads to an error as it doesn't rexecute the exact same query.

Steps to Reproduce

const schema = new Schema().pre("find", () => console.log("pre hook function"))
const myModel = model("Test", schema)
const query = myModel.find()

await query.clone() // Do nothing
await query // Log "pre hook function"

The only workaround is a "deep copy":

const schema = new Schema().pre("find", () => console.log("pre hook function"))
const myModel = model("Test", schema)
const initialQuery = myModel.find()

// Magic is here
const queryCloned = initialQuery.model.find(initialQuery.getFilter())
await queryCloned() // Log "pre hook function"

Expected Behavior

Execute the schema hooks on a cloned Query.

@IslandRhythms IslandRhythms added the confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. label Aug 31, 2022
@IslandRhythms
Copy link
Collaborator

const mongoose = require('mongoose');
const { Schema } = mongoose;


async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await mongoose.connection.dropDatabase();
  const schema = new Schema().pre("find", () => console.log("pre hook function"))
  const myModel = mongoose.model("Test", schema)
  const query = myModel.find()

  const result = await query.clone() // Do nothing
  const res = await query // Log "pre hook function"
  console.log(result);
  console.log(res);
}

run();

@vkarpov15 vkarpov15 added this to the 6.5.6 milestone Sep 8, 2022
vkarpov15 added a commit that referenced this issue Sep 12, 2022
fix(query): use correct Query constructor when cloning query
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

Successfully merging a pull request may close this issue.

3 participants