existing mogodb collection with mongoose
I'm trying to run mongoose schema validation on pre-existing collections. The collections were created with mongoose so the documents are generally correct, but if the schema changes in some way, fields added/removed, types changed, etc. I have to write a script to make those changes manually to the collection.
I decided that a more flexible/reusable solution would be to just run the schema validation over the whole collection. However, that doesn't seem to be as easy as I thought it would be.
My problem is that currently, the only time the validation gets run is on document creation and an update using the save()
method. Save injects $set
so it doesn't overwrite the document, and only validates fields that are being written. So, for example, if field foo
got changed from a string to a number with default 0, any documents with strings already in foo
need to be found and set to default.
I am currently retrieving all docs, iterating over each one and calling .save()
, if there is a type error, I delete the offending field using err.path
and try to save again, repeating util there are no errors. I thought for sure that would set any field that doesn't match the schema to its default, but save()
doesn't overwrite the doc, so if a field exists in the db but not in the doc being saved it leaves it alone and nothing happens.
There is an overwrite option on mongooses update method, but update doesn't run validation so I'm stuck.
链接地址: http://www.djcxy.com/p/60690.html上一篇: 猫鼬自动增量
下一篇: 现有mogodb收集与猫鼬