I have created a mongoose schema in the past with a certain field that I want to remove, or rather convert into an array now.
An instance of the original version looks something like this:
{ item: 'My awesome item' } // not showing other fields to save space
Which I want to change to something like this:
{ items: [ { name: 'My awesome item' } ] }
I changed the field in the schema to be an array of the above format. Now, in my database I still have old documents that have the item field and I want to convert them like so:
const models = await MyModel.find().exec()
for (const model of models) {
if (model.item) {
model.items = [ { name: model.item } ]
model.item = undefined
await model.save()
}
}
Now the weird thing is, by printing my models I see that the docs I get through find()
do indeed have the item
field. However, mongoose already tried to pack it into the new schema so the model that I retrieve looks like this:
{ item: 'My awesome item', items: [] }
Hence, it already created the items
field and still has the old item
field. My problem now is that by mongoose packing it into the adjusted schema, I can't access the existing item
field anymore. model.item
is undefined
although when printing the entire model
object it shows.
Can anybody help how to solve this?