Ability to add properties that aren't defined on the schema
See original GitHub issueI have a use case where I read some documents from the database and then do some calculations on their data, after which I’d like to append this data to the documents as new properties.
In Mongoose, this is not possible unless the properties are defined in the schema. E.g. Mongoose will not allow you to add unknown properties that you haven’t defined on the schema in advance.
So the “normal” solution would be to convert the documents to plain objects or JSON with toObject
or toJSON
first.
This works fine in most cases, but in my specific case I have defined several methods on the document model as well, and I’d like to retain the ability to call them for as long as I can. Converting the documents to plain objects or JSON obviously discards the methods, making it impossible to use them further down the data processing chain.
The only apparent work around would be to change the order of data processing or store both the models and JSON objects separately, but this is a bit of a drag if you’re passing data around via promises or the req
object.
I’m wondering if it would be hard to implement a new flag for Mongoose schema’s which when enabled, will in fact let you add “new” or unknown properties to a document. This data can be ignored when a document is saved or validated, but appended when a document is converted to JSON or plain object.
Another use case for it that I encountered is to append some temporary meta data to my documents. Again, with the data processing example, I’d like to maybe find some additional data/information about my documents, and attach this to them temporarily for later use, again without losing access to my document methods.
Thoughts?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:2
- Comments:19 (6 by maintainers)
I don’t think they do, I have had to access them via
document._doc.someProperty
, because they wouldn’t get attached to the actual model based document, and as a result, also didn’t show up intoJSON()
output. I assumed this is a feature of Mongoose. E.g.:Nope it’s perfectly valid for a virtual to set a property that isn’t on the schema (modulo strict mode).
With the default strict mode, you can set whatever properties on the object you want, they just won’t get persisted to the db.