-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Instantiating model with model instance causes confusion #5779
Comments
That warning is to prevent people from mixing up |
@vkarpov15 i think @maximilianschmitt is just saying that they would like a warning from mongoose if you try to pass a mongoose doc to the Model constructor. Additionally, it errors if you do |
Yeah, the problem is that I intuitively expect mongoose to create a copy (or reference) of the model instance if I pass it into the model constructor again. Instead, I'm not exactly sure what happens but there are issues with version keys (promise rejecting with By the way, var oid1 = new mongodb.ObjectId()
var oid2 = new mongodb.ObjectId(oid1)
console.log(oid1 === oid2) // true |
This may seem contrived, but for clarification that is how we came upon this: In our codebase we usually call constructor(document) {
this.document = new Document(document)
} First this was only used to create new documents that weren't in the database before. For that it works fine. Later we added routes that changed documents already in the database. The function we use to query the database was one that actually returns a mongoose document and does not use constructor(document) {
if (document instanceof Document) {
this.document = document;
} else {
this.document = new Document(document);
}
} Which works now. (it still has an edge case where it fails when being passed a lean document with an So what we're asking for is just an Error in case someone is as oblivious as us. Or having it behave like |
Thanks for the detailed clarification @despairblue . I think changing it so that |
Do you want to request a feature or report a bug?
Not sure if this is a bug, but it's behaviour we tripped over and spent about 4-5 hours debugging.
What is the current behavior?
Running the following piece of code, there will be a promise rejection "VersionError":
The issue is that we're passing a model instance to the model constructor.
What is the expected behavior?
Can mongoose throw an error or warn in case you pass a model instance into a model constructor?? There is already a little safeguard for passing a schema as the second argument to the model constructor:
Please mention your node.js, mongoose and MongoDB version.
The text was updated successfully, but these errors were encountered: