mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

The Model constructor mutates its inputs

Open nomcopter opened this issue 5 years ago • 2 comments

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

What is the current behavior? Instantiating models mutates the input arguments. We ran into it with object ID arrays but there may be more cases.

The code below prints: Assertion failed: after

If the current behavior is a bug, please provide the steps to reproduce.

const mongoose = require('mongoose');

const MutatingSchema = new mongoose.Schema({
  objectIdArray: [
    {
      type: mongoose.Schema.Types.ObjectId,
    },
  ],
});
const MutatingModel = mongoose.model('MutatingModel', MutatingSchema);
const id = '614bf569793eb0b25e631952';
const objectIdArray = [id];
console.assert(id === objectIdArray[0], 'before');
new MutatingModel({ objectIdArray });
console.assert(id === objectIdArray[0], 'after');

Stack trace of where this issue appears to be happening:

    at ObjectId.SchemaType.applySetters (/.../mongoose/lib/schematype.js:1122:12)
    at SchemaArray.cast (/.../mongoose/lib/schema/array.js:385:32)
    at SchemaArray.SchemaType.applySetters (/.../mongoose/lib/schematype.js:1122:12)
    at model.$set (/.../mongoose/lib/document.js:1386:20)
    at model.$set (/.../mongoose/lib/document.js:1128:16)
    at model.Document (/.../mongoose/lib/document.js:148:12)
    at model.Model (/.../mongoose/lib/model.js:106:12)

What is the expected behavior? Mongoose to not mutate inputs to the Model constructor.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version. Node: v14.15.1 Mongoose: v6.0.6 MongoDB: v4.1.1

nomcopter avatar Sep 23 '21 03:09 nomcopter

For what it is worth, running these same reproduction steps on mongoose v5.13.9 does not seem to produce the same issue

mewelling avatar Sep 23 '21 13:09 mewelling

objectIdArray goes from holding a string id to holding an object id and this did not happen in mongoose 5.x

IslandRhythms avatar Sep 23 '21 15:09 IslandRhythms