Can't instance a model from mongoose after update from v4 to v6
See original GitHub issueI’m submitting a…
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Duplicated issue https://github.com/nestjs/nest/issues/2585 but I was not sure where should I actually report this bug, so, I am also opening it here
Current behavior
I was using v4 of nestjs and i was instancing new mongoose model with
import { model } from 'mongoose';
const someModel: Model = model(modelName, someSchema)
After upgrading nest to v6, this is not working anymore. I switched to officially suggested way of using it with @InjectModel()
, but there is still a case where I have to instance model like this.
I want to write a prehook in which I want to do some query on some model.
But when I do it like this, it can’t execute a query, and it does not throw an error. But it stops execution of code.
My assumption is that somehow, mongoose.connection
is not set globally, so, model does not know through which connection to execute query.
Expected behavior
Expecting that using mongoose.model()
still can execute query, or if it is possible somehow to extract connection from app.module
Minimal reproduction of the problem with instructions
import { model } from 'mongoose';
Schema.pre('save', function (next: Function): void {
const someModel: Model = model(modelName, schema);
someModel.countDocuments(query).then((result: number) => {
return next(true);
}).catch((error) => next(error));
});
Some example code, which should be executed, not providing full example, I think it is not necessary. I can’t use this https://docs.nestjs.com/recipes/mongodb, because I don’t need this feature in some provider or module, so no option to inject it
What is the motivation / use case for changing the behavior?
Environment
Nest version: 6.4.0
For Tooling issues:
- Node version: 8.13
- Platform: Linux, docker
Others:
- Mongoose: 5.6.3
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:10 (4 by maintainers)
@NenadJovicic for now i doing something like this
If I had to bet, it has to deal with how you import
mongoose
. Try a named import likeimport * as mongoose from 'mongoose'
For further support please use our Discord channel (Support). We are using GitHub to track Bug Reports, Feature Requests, and Regressions.