Skip to content

Versioning does not work if the versionKey option for toObject is set to false when using insertMany #14344

@juona

Description

@juona

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

Node.js version

18.18.2

MongoDB server version

5

Typescript version (if applicable)

No response

Description

Quite a specific issue here...

Setting the schema option toObject to { versionKey: false } interferes with the versioning mechanism when Model.prototype.insertMany() is used. This affects optimisticConcurrency too.

Debug logs print:

Mongoose: mymodels.insertMany([ { name: 'x', _id: new ObjectId('65c6b71554b43144d136c12f') } ], {}) 

Using Model.prototype.create() works correctly:

Mongoose: mymodels.insertOne({ name: 'x', _id: ObjectId("65c6b745afcd1f760cc117ba"), __v: 0 }, {}) 

Not surprising since the logic for the two methods is deliberately completely separate. Just makes me wonder if there are more edge cases like this one? I.e. what are some other ways of inserting a new document into the database that might not be covered? Perhaps this is something worth looking into.

Steps to Reproduce

import mongoose from "mongoose"; import { MongoMemoryReplSet } from "mongodb-memory-server"; console.log("connecting..."); const mongoDbService = await MongoMemoryReplSet.create(); await mongoose.connect(mongoDbService.getUri()); console.log("connected!"); const schema = new mongoose.Schema( { name: String }, // Could be `optimisticConcurrency` as well { versionKey: "__v", toObject: { versionKey: false } } ); const Model = mongoose.model("MyModel", schema); // Substituting this for `create()` fixes the problem await Model.insertMany([{ name: "x" }]); const doc = await Model.findOne(); console.log(doc.__v); // prints `undefined` when using `insertMany`, and `1` when using `create` await mongoose.disconnect(); console.log("done!") process.exit(0);

Expected Behavior

My reasoning is that I set toObject: { versionKey: false } because I don't wish to have this field in the output when I invoke toObject(). I don't believe it should affect the internal mechanics of the versioning feature though.

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