You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
letmodelName="";letcollectionName="";if(thisinstanceofQuery){modelName=this.model.modelName;collectionName=this.model.collection.name;}elseif(thisinstanceofDocument){letdoc=this;// Subdocuments seem to not have model/collection names so keep going up to the parentwhile(isSome(this.$parent())&&doc!==this.$parent()){doc=this.$parent()asDocument;}modelName=(doc.constructorasany).modelName;collectionName=doc.collection.name;}
But this does not work either in the document case, sometimes I get TypeError: Cannot read properties of undefined (reading 'name') because doc.collection is sometimes undefined. It seems like subdocuments also behave slightly differently than documents in this case.
Surely documents should know which model they came from, so there must be some way to do this. Help would be appreciated; thanks!
The text was updated successfully, but these errors were encountered:
Can you provide a repro script that demonstrate the case where doc.collection is undefined? That's unexpected.
Re: types for doc.constructor, we'll fix that.
Also, instead of using a while loop to get the root document, you can just use doc = this.ownerDocument().
vkarpov15
added
typescript
Types or Types-test related issue / Pull Request
and removed
help
This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary
help wanted
labels
Sep 26, 2023
Prerequisites
Mongoose version
6.12.0
Node.js version
18
MongoDB version
6
Operating system
None
Operating system version (i.e. 20.04, 11.3, 10)
No response
Issue
I'm trying to write a query/document middleware that logs the model name + collection name in certain circumstances.
I looked at https://mongoosejs.com/docs/6.x/docs/api/document.html, and the first problem I ran into is that model/collection name are not documented in the types.
Then I tried writing:
But this does not work either in the document case, sometimes I get
TypeError: Cannot read properties of undefined (reading 'name')
becausedoc.collection
is sometimes undefined. It seems like subdocuments also behave slightly differently than documents in this case.Surely documents should know which model they came from, so there must be some way to do this. Help would be appreciated; thanks!
The text was updated successfully, but these errors were encountered: