Skip to content

'document' parameter is a function in post save middleware #13026

@MZPL

Description

@MZPL

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.9.1

Node.js version

19.5.0

MongoDB server version

6.0.4

Typescript version (if applicable)

No response

Description

Hi. When bulkSave() is called, it fires post save middleware, but for some reason, the doc parameter is a function, but typings indicate it should be a document. Using this works tho.
Apart from that, what is the proper way to get a document? Docs list these 2 ways, but I couldn't find the difference between them in the docs.

Steps to Reproduce

import mongoose from "mongoose";

mongoose.set("debug", true);
await mongoose.connect("mongodb://127.0.0.1:27017/mongooseissue");

const schema = new mongoose.Schema({ foo: Boolean, bar: Boolean });

schema.post("save", function (doc) {
    // 'doc' is typed as:
    // mongoose.Document<unknown, any, { foo?: boolean | undefined; bar?: boolean | undefined; }> & { foo?: boolean | undefined; bar?: boolean | undefined; } & { _id: mongoose.Types.ObjectId; }
    console.log("this:");
    console.log(this);
    console.log("doc:");
    console.log(doc);
})

const TestModel = mongoose.model("test", schema);

async function one() {
    const doc = new TestModel({ foo: true, bar: true });
    await doc.save();
    // 'this' and 'doc' are printed in post middleware, they're equal
}

async function two() {
    const docs = await TestModel.find({}).exec();
    docs.forEach(doc => {
        doc.foo = false;
    })
    await TestModel.bulkSave(docs);
    // 'this' is a document
    // 'doc' parameter is a function, why?
}

console.log("One");
await one();

console.log("Two");
await two();

Expected Behavior

The doc parameter is a document

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions