/index.js Secret
Created
March 19, 2024 09:12
mongoose-8325e563-issue-repro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose'); | |
const MONGO_URI = 'mongodb://127.0.0.1:47018/mongoose-issue-test'; | |
const childSchema = new mongoose.Schema(); | |
childSchema.virtual('name') | |
.set(function (values) { | |
for (const [lang, val] of Object.entries(values)) { | |
this.set(`name.${lang}`, val); | |
} | |
}) | |
.get(function () { | |
return this.$__getValue(`name.${this.lang}`); | |
}); | |
childSchema.add({name: {en: {type: String}, de: {type: String}}}); | |
const ChildModel = mongoose.model('Model', childSchema); | |
const ParentModel = mongoose.model('Parent', new mongoose.Schema({ | |
children: [childSchema], | |
})); | |
(async () => { | |
mongoose.connect(MONGO_URI); | |
const child = await ChildModel.create({name: {en: 'Stephen', de: 'Stefan'}}); | |
child.lang = 'en'; | |
console.log(child.name); | |
const parent = await ParentModel.create({ | |
children: [{name: {en: 'Stephen', de: 'Stefan'}}], | |
}); | |
parent.children[0].lang = 'de'; | |
console.log(parent.toJSON({getters: true})); | |
mongoose.disconnect(); | |
})(); | |
/* | |
output up to mongoose@6.3.4: | |
Stephen | |
{ | |
children: [ | |
{ | |
_id: new ObjectId("65f88a0fa4c14240fb3482c5"), | |
name: 'Stefan', | |
id: '65f88a0fa4c14240fb3482c5' | |
} | |
], | |
_id: new ObjectId("65f88a0fa4c14240fb3482c4"), | |
__v: 0, | |
id: '65f88a0fa4c14240fb3482c4' | |
} | |
output with mongoose >=3.6.5: | |
Stephen | |
[…]/node_modules/mongoose/lib/document.js:3895 | |
branch[part] = clone(val, options); | |
^ | |
TypeError: Cannot create property 'de' on string 'Stefan' | |
at applyGetters ([…]/node_modules/mongoose/lib/document.js:3895:22) | |
at Document.$toObject ([…]/node_modules/mongoose/lib/document.js:3544:5) | |
at Document.toJSON ([…]/node_modules/mongoose/lib/document.js:4013:15) | |
at clone ([…]/node_modules/mongoose/lib/helpers/clone.js:52:17) | |
at cloneArray ([…]/node_modules/mongoose/lib/helpers/clone.js:164:14) | |
at clone ([…]/node_modules/mongoose/lib/helpers/clone.js:35:12) | |
at applyGetters ([…]/node_modules/mongoose/lib/document.js:3895:24) | |
at Document.$toObject ([…]/node_modules/mongoose/lib/document.js:3544:5) | |
at Document.toJSON ([…]/node_modules/mongoose/lib/document.js:4013:15) | |
at […]/index.js:36:22 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment