nestjs / mongoose Goto Github PK
View Code? Open in Web Editor NEWMongoose module for Nest framework (node.js) πΈ
Home Page: https://nestjs.com
License: MIT License
Mongoose module for Nest framework (node.js) πΈ
Home Page: https://nestjs.com
License: MIT License
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
There is currently no way to add mongoose schema hooks that depend on any @Injectable()
services using the nest MongooseModule
.
I could submit a non-breaking PR for this in pretty short order, but I'd need further guidance than exists in your contributing docs.
var express = require('express');
var router = express.Router();
var mongodb=require('mongodb');
var db = mongodb('mongodb+srv://database1:********@cluster0-c88kl.mongodb.net/test?retryWrites=true'['tasks'])
router.get('/tasks',function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
error:(node:4544) UnhandledPromiseRejectionWarning: Error: URL malformed, cannot be parsed
at module.exports
The connection is being created with the call to mongoose.connect(uri, options)
creating the default database connection object. The constant DbConnectionToken
is used for the database provider name.
This both things make it impossible to use multiple connections.
I am working on a PR to enable it, but am not sure if there is a fundamental reason why is it implemented as it is.
I have two models imported to ApplicationModule:
@Module({
imports: [
MongooseModule.forRoot(process.env.DB_URL),
UsersModule,
AuthModule
],
controllers: [AppController],
components: []
})
export class ApplicationModule {}
@Module({
imports: [
MongooseModule.forFeature([{
name: 'User',
schema: UserSchema
}]),
forwardRef(() => AuthModule)
],
components: [],
controllers: [UsersController],
exports: []
})
export class UsersModule {
}
Inside the AuthModule I need to be able to access the UserSchema model, but im getting:
Error: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.
when trying to use @InjectModel(UserSchema).
What am i missing?
Typegoose stop working after upgrade @nestjs/mongoose from version 4.0.0 to 5.0.0.
[x] Regression
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
When upgrade to version 5.0.0. I cannot make any query to my database.
Should be working like version 4.0.0
Here a simple repository. It is working on version 4.0.0. Then when you upgrade, it's not working anymore. The working part of typegoose is existingMongoose: mongoose
.
import * as mongoose from 'mongoose';
import { prop, Typegoose } from 'Typegoose';
export class UserSchema extends Typegoose {
@prop({ required: true })
firstName!: string;
@prop({ required: true })
lastName!: string;
@prop({ required: true })
username!: string;
@prop({ required: true })
password!: string;
}
export const User = new UserSchema().setModelForClass(UserSchema, {
schemaOptions: { collection: 'Users', timestamps: true },
existingMongoose: mongoose
});
First when using mongo in nest project, I prefer using Typegoose. It offers a better schema declaration and typings. It is similar to sequelize-typescript when it comes to mongo design. It saving a lot of time to declare interfaces for every mongo schema.
Nest version: 5.0.1
For Tooling issues:
- Node version: 8.10.0
- Platform: Windows
Others: ...
[ ] Regression
[ ] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
The actual Mongoose options passed to the library are not typesafe:
We could make MongooseModuleOptions
extend ConnectionOptions
to provide typesafeness
Typesafeness
Nest version: 6
For Tooling issues:
- Node version: Any
- Platform: Any
Others:
Could not find a declaration file for module 'mongoose'. '/home/dev/Documents/projects/nest/petshop/node_modules/mongoose/index.js' implicitly has an 'any' type.
Try npm install @types/mongoose
if it exists or add a new declaration (.d.ts) file containing declare module 'mongoose';
Nest: 6.6.4
NodeJS: 12.7.0
Typescript: 3.5.3
package.json
"dependencies": {
"@nestjs/common": "^6.0.0",
"@nestjs/core": "^6.0.0",
"@nestjs/mongoose": "^6.1.2",
"@nestjs/platform-express": "^6.0.0",
"mongoose": "^5.6.9",
"reflect-metadata": "^0.1.12",
"rimraf": "^2.6.2",
"rxjs": "^6.3.3"
},
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I have a service that uses the @InjectConnection decorator in it's constructor.
I am unable to instantiate a testingModule for this service. 'Nest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context.'
I would like to be able to inject a mock of the connection object so that I can unit test the service.
Service constructor:
constructor(@InjectConnection() private readonly mongooseConnection: Mongoose,
@Inject(Modules.Logger) private readonly logger: Logger) {
this.attachmentGridFsRepository = gridfs({
collection: 'attachments',
model: Schemas.Attachment,
mongooseConnection: this.mongooseConnection,
});
this.attachmentRepository = this.attachmentGridFsRepository.model;
}
Test module constructor:
const module: TestingModule = await Test.createTestingModule({
imports: [
WinstonModule.forRoot({
transports: [
new transports.Console({
level: 'info',
handleExceptions: false,
format: format.combine(format.json()),
}),
],
}),
],
providers: [AttachmentsService, {
provide: getConnectionToken(''),
useValue: {},
}],
}).compile();
service = module.get<AttachmentsService>(AttachmentsService);
I would like to be able to unit test this service.
Nest version: 5.4.0
For Tooling issues:
- Node version: 10.13.0
- Platform: Windows
Others:
[ ] Regression
[ x] Bug report
[x ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
In Mongo for the same schema
TypeSchema
name: string
_id: ObjectID
is used by multiple collections:
CategoriesCollection
TypesCollection
When you use the mongooseModule, you can define well this collections, but when you inject them on service with @InjectModel(TypeSchema), only one Model is reference.
This is because you inject it with schema as parameters, injectModel as name collections will be better to avoid this.
Use the same schema for multiple collections.
Nest version: 4.5.9
For Tooling issues:
- Node version: v8.9.4
- Platform: Windows
Others:
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
If you want to create an index in the model you do.
const ClientSchema = new Schema({
client_name: String,
client_phone: String,
client_email: String,
});
// create this manually for now
ClientSchema.index({
client_phone: 1,
client_email: 1,
},{
unique: true,
});
return ClientSchema;
@Module({
imports: [MongooseModule.forFeature([{ name: 'Client', schema: ClientSchema }])],
})
But there is no impact in database.
There should be indexes created in the database collection.
Nest version: 6.0.0
For Tooling issues:
- Node version: 10.15.3
- Platform: Mac
Others:
[ ] Regression
[ ] Bug report
[x] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
file: src/app/app.controller.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AuthModule } from '../auth/auth.module';
import { UsersModule } from '../users/users.module';
import { MongooseModule} from '@nestjs/mongoose';
import {dbConn, dbUser, dbPass } from './app.constants';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [],
imports: [
AuthModule,
UsersModule,
MongooseModule.forRoot(dbConn, {
useNewUrlParser: true,
user: dbUser,
pass: dbPass,
})
]
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(true).toBe(true);
});
});
});
running npm script again,
npm test
with adjustments
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AuthModule } from '../auth/auth.module';
import { UsersModule } from '../users/users.module';
import { MongooseModule} from '@nestjs/mongoose';
import {connections} from 'mongoose'; // added
import {dbConn, dbUser, dbPass } from './app.constants';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [],
imports: [
AuthModule,
UsersModule,
MongooseModule.forRoot(dbConn, {
useNewUrlParser: true,
user: dbUser,
pass: dbPass,
})
]
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(true).toBe(true);
});
});
// added
afterEach( (done) => {
connections[1].close(() => {
done();
});
})
});
For Tooling issues:
[System Information]
- OS Version : Linux 4.15
- NodeJS Version : v12.8.1
- NPM Version : 6.10.3
[Nest Information]
- platform-express version : 6.0.0
- mongoose version : 6.1.2
- passport version : 6.1.0
- common version : 6.0.0
- core version : 6.0.0
- jwt version : 6.1.1
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Currently, we have to create an interface for our entities and create a schema as well. You can quickly have a schema file, an interface file and maybe a graphql file (if used).
users/
| - users.schema.ts
| - users.graphql
| - users.interface.ts
| - users.dto.ts
| - users.module.ts
Can't we use something like typegoose but extended to everything? (Dto, Mongoose, Graphql, etc) just from different decorators?
Thank you!
[ ] 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.
In Version 6.3.0 of the Mongoose Module the MongooseModuleOptions (e.g useNewUrlParser, ...) doesn't work anymore.
In Version 6.1.2 they work.
Enable MongooseModuleOptions in current version
Nest version: 6.1.7
Mongoose version: 5.8.10
@nestjs/mongoose Version: 6.3.0
For Tooling issues:
- Node version: 12.14. 1
- Platform: Windows
Others:
there is no documentation available for that
[ ] Regression
[x] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
import * as existsValidator from 'mongoose-exists';
import * as uniqueValidator from 'mongoose-beautiful-unique-validation';
@Injectable()
export class MongoService implements MongooseOptionsFactory {
createMongooseOptions(): MongooseModuleOptions {
mongoose.plugin(existsValidator);
mongoose.plugin(uniqueValidator);
mongoose.set('debug', true);
return {
uri: 'mongodb://localhost:27017/testdb',
useNewUrlParser: true,
useCreateIndex: true,
};
}
}
MongooseModule.forRootAsync({
useClass: MongoService,
})
export const FavoritSchema = new Schema({
name: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'user',
validate: {
isAsync: true,
validator: (v, cb) => {
/*setTimeout(function() {
cb(true);
}, 500);*/ // working
// mongoose.model('user').findById(v).exec().then(user => cb(!!user)).catch(() => cb(false));
// not working
},
message: 'do not exists!',
},
required: true,
},
}, {
toJSON: {
versionKey: false,
virtuals: true,
transform: (doc, ret) => {
delete ret._id;
},
},
});
export const FavoritSchema = new Schema({
name: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'user',
exists: true // not working
}, {
toJSON: {
versionKey: false,
virtuals: true,
transform: (doc, ret) => {
delete ret._id;
},
},
});
[System Information]
OS Version : Linux 4.15
NodeJS Version : v8.14.0
NPM Version : 6.4.1
[Nest Information]
mongoose version : 5.2.2
common version : 5.4.0
core version : 5.4.0
"mongoose": "^5.4.2",
"mongoose-exists": "^0.6.4",
For Tooling issues:
- Node version: XX
- Platform:
Others:
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.
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.
Expecting that using mongoose.model()
still can execute query, or if it is possible somehow to extract connection from app.module
Nest version: 6.4.0
For Tooling issues:
- Node version: 8.13
- Platform: Linux
Others:
Mongoose verison: 5.6.3
Let's say we're having two schemas called conversation
and message
.
MessageSchema
:
export const MessageSchema = new mongoose.Schema({
Created: { type: Date, default: Date.now },
ConversationID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'conversation'
},
SenderID: mongoose.Schema.Types.ObjectId,
Text: String, // Message Text oder Filename
}
ConversationSchema
:
export const ConversationSchema = new mongoose.Schema({
Title: String,
Description: String,
Participants: [{
type: mongoose.Schema.Types.ObjectId // userIDs
}],
Created: {
type: Date,
default: Date.now
}
});
Whenever a conversation is deleted I want mongoose to automatically delete all related messages. Mongoose has a functionality called Middleware
for that (also called pre and post hooks).
Docs: http://mongoosejs.com/docs/middleware.html
The problem is, that I'll need the MessageModel
instance for the remove query.
ConversationSchema.post('findOneAndRemove', function (err, doc, next) {
// Remove messages related to this conversation
Message.remove({
ConversationID: doc._id
}).then(() => {
next();
});
});
How can I retrieve the model instance? As far as I understand there is no nestjs injection available for schemas.
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I use a custom MongoDB module that connects (create a connection) in the forRoot
. But when the app closes, there is no way instruct and disconnect the database.
I got this situation during my e2e test, jest hangs waiting for a promise to be resolved and it comes from the DB connection having his connection.
During the app.close()
, I would like my services connection to be closed properly.
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import * as nock from 'nock';
import * as Qs from 'qs';
import { Collection } from 'mongodb';
import * as request from 'supertest';
import { AppModule } from '../../src/app.module';
import { getModelToken } from 'src/core/mongodb/mongodb.utils';
import { Snap } from 'src/snaps/model/schema/snaps.schema';
import { DateManager } from 'src/core/utils/date-manager.service';
import { SnapModel } from 'src/snaps/model/snaps.model';
describe('SnapController (e2e)', () => {
let app: INestApplication;
let snapsCollection: Collection<Snap>;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
app.useGlobalPipes(new ValidationPipe());
await app.init();
snapsCollection = app.get<Collection<Snap>>(getModelToken('snaps'));
});
beforeEach(async () => {
await snapsCollection.deleteMany({});
});
afterEach(async () => {
nock.cleanAll();
});
afterAll(async () => {
// Disconnect my db connection,
await app.close();
});
describe('/snaps (POST)', () => {
// it blablavbla...
});
});
I know I could manually disconnect my DB in the after here getting the service by my hand, but maybe the module may need to implement a close
method to handle such a case.
Or should I use https://docs.nestjs.com/fundamentals/lifecycle-events?
Let me know what you think.
Nest version: 6.7.2
For Tooling issues:
- Node version: 12.13.0
- Platform: Linux and Mac
WARNING: The useMongoClient
option is no longer necessary in mongoose 5.x, please remove it
π
First of all, thanks for the great job on nestjs and its ecosystem π₯
That being said, given that the connection to the MongoDB instance is initially established in the forRoot(...)
method, what is the recommended approach to catching and handling an initial connection error?
So after opening the issue in the wrong repository, here I'm again.
[ ] Regression
[ ] Bug report
[*] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Testing e2e with mongoose is done via mockgoose. A connection has to be created, injected as provider (in AppModule)
Also models cannot be registered with the mongoose.forFeature()
-method, which is very convenient.
Im refering to this part of the documentation (https://docs.nestjs.com/recipes/mockgoose)
It would be nice to get a TestingModule which can be used in e2e tests to mock the mongoose.forRoot()
-method.
Something like the HttpClientTestingModule from angular.
Also it would be great if there would be a way to add fake data, when creating the connection to the mocked database.
Currently it is cumbersome to setup a mongodb connection (either over mockgoose or a other collection in the database). It would be very convenient to have a built-in way to setup a connection which works together with the other parts of the mongoose package.
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I have to call a configuration service before loading mongoose schema module or plugin, cause I need to use a key for encrypting.
support to load mongoose module or plugin after getting configurations.
import { Document } from 'mongoose';
export class TestSchema extends Document{
readonly test: String;
}
export const initMongoosePlugin = () => {
TestSchema.plugin(plugin, {
fields: ['test'],
secret: global['KEY'], // init it in main.ts
});
};
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const appService: AppService = app.get(AppService);
global['KEY'] = await appService.getKey();
// init Mongoose Plugin
initMongoosePlugin();
app.use(requestIp.mw());
await app.listen(3000));
}
bootstrap();
We have a configuration service to manager all configurations, so we need to call it for configurations to init our app.
Nest version: 6.9.0
For Tooling issues:
- Node version: v10.16.0
- Platform: Mac / Windows
Others:
This is one of those "please do this to be kind to users" items. The repository
field in package.json
needs to be added and set to point back here. It took me a hot minute to figure out where the repo for the module was. This will go a ways towards a positive Developer Experience.
[ ] 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.
can't set property 'family' of options in MongooseModule.forRoot
console log when compile:
src/app.module.ts:24:58 - error TS2345: Argument of type '{ useNewUrlParser: boolean; useCreateIndex: boolean; useFindAndModify: boolean; autoIndex: boolean; reconnectTries: number; reconnectInterval: number; poolSize: number; bufferMaxEntries: number; connectTimeoutMS: number; socketTimeoutMS: number; family: number; }' is not assignable to parameter of type 'MongooseModuleOptions'.
Types of property 'family' are incompatible.
Type 'number' is not assignable to type '4 | 6'.
24 imports: [BillsModule, MongooseModule.forRoot(mongoDB, options)],
be able to set property 'family' to 4
my optionsοΌ
const options = {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0,
connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
}
Nest version: 6.10.14
@types/mongoose: 5.7.0
For Tooling issues:
- Node version: 12.9.1
- Platform: Windows
Others:
[ ] Regression
[x] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Some times the db command is hanging and returned promise will never resolve. It seems that we should use createConnection
with db.model(...)
and connect
with mongoose.model(...)
.When i change to use connect, everything works fine, So maybe this plugin should update to prevent this case. please see: https://stackoverflow.com/questions/22786374/queries-hang-when-using-mongoose-createconnection-vs-mongoose-connect
db command not hang
it maybe difficult to reproduce my case, there is some log output:
public create(docs: Partial<T>): Promise<T> {
console.log('inner create: start');
const pro = this._model.create(docs);
console.log('inner create: end', pro);
return pro;
}
public async createComment(data: CommentDto, req: Request) {
console.log('create comment service:');
const comment = await super.create(data);
console.log('create comment service after:', comment);
}
// log:
create comment service:
inner create: start
inner create: end Promise { <pending> } // hang there
catch error in timeout interceptor:
Nest version: "@nestjs/core": "^6.0.4"
plugin version: "@nestjs/mongoose": "^6.0.0"
For Tooling issues:
- Node version: v10.15.3
- Platform: Mac
Others:
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I am using mongoose plugin which depends on mongoose.connection
As I wrote in some other issues (#27 and #109) there was a problems after nest upgrade from 4 to 6 because you started to use createConnection()
instead of connect()
.
To have an option to get connection before models are initialized. Would be good to have it in MongooseModule.forRoot()
or MongooseModule.forRootAsync()
or somewhere else
Plugin that I am using is mongoose-id-validator
which was using mongoose.connection
to instance a model and search for a reference that I have in Document
. I had to change this plugin after upgrading nest
My question is, is there some official way of getting connection that nest establish to mongo, after it is created, but before models are generated with MongooseModule.forFeature
(plugins can't be applied on models that are already initialized), because plugin that I am using got as an option to provide a connection that should be used.
Described in Current behavior
Nest version: 6.8.5
For Tooling issues:
- Node version: XX
- Platform:
Others:
Hi, is there any future plan for supporting mongoose discriminators?
can you help me?
mongoose one to one, one to many, many to many.
I need that.
[ ] Regression
[ ] Bug report
[x ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Nest version: X.Y.Z
For Tooling issues:
- Node version: XX
- Platform:
Others:
[ ] 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
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.
Expecting that using mongoose.model()
still can execute query, or if it is possible somehow to extract connection from app.module
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
Nest version: 6.4.0
For Tooling issues:
- Node version: 8.13
- Platform: Linux, docker
Others:
- Mongoose: 5.6.3
[ ] Regression
[ ] Bug report
[ x ] Feature request
[ x ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
We want to usemongoosastic in our project to store certain collections in ElasticSearch.
Our code structure is a bit different than the traditional examples given in Nest docs.
Our models are created independent of the service code. We create models and push to them to a private npm repository so that it can be reused across various other modules.
Here is a sample model example:
import * as mongoose from 'mongoose';
import { AddressInfoSchema } from '@private-package/address-model';
export const StopSchema = new mongoose.Schema({
_id: String,
stopName: String,
addressInfo: AddressInfoSchema,
stopType: { type: String, enum: ['PARKING', 'WAYPOINT', 'STOP'] }
}, {
versionKey: false,
timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }
});
And we are importing it into our services like so:
// imports
@Module({
imports: [
MongooseModule.forFeature([
{ name: 'Stop', schema: StopSchema },
]),
],
// rest of the code
As per the mongoosastic docs, To have a model indexed into Elasticsearch simply add the plugin.
So We are adding the plugin like so,
// imports
@Module({
imports: [
MongooseModule.forFeature([
{ name: 'Stop', schema: StopSchema.plugin(mongoosastic, { hosts: ['localhost:9200','anotherhost:9200']}) },
]),
// rest of the code
When injecting this model in the controller, We are not able to access the mongoosastic functions. Also when using save()
methods, it is not indexing to ElasticSearch.
We should be able to use the plugins in @Module
declarations.
Mentioned in Current behavior section
To be able to use plugins for mongoose models, independent of whether the models are included in NestJS projects.
Nest version: X.Y.Z
````
"@nestjs/common": "^5.0.0-beta.6",
"@nestjs/core": "^5.0.0-beta.6",
"@nestjs/elasticsearch": "^0.1.2",
"@nestjs/microservices": "^5.0.0-beta.6",
"@nestjs/mongoose": "^5.0.0",
````
For Tooling issues:
- Node version: XX
````
> node -v
v10.10.0
````
- Platform: All
Others:
[ ] 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.
Hello there, when i try to import {MongooseModule} from @nestjs/mongoose it show up that "node_modules/@nestjs/mongoose has no exported member "MongooseModule".
When i check nestjs/mongoose folder i find out that "./dist" is missing. How to fix this bug?
Nestjs version:
"@nestjs/common": "^6.7.2",
"@nestjs/core": "^6.7.2",
"@nestjs/mongoose": "6.2.1",
"@nestjs/platform-express": "^6.7.2",
For Tooling issues:
- Node version: 12.14.0
- Platform: Debian 10
##Solution
Install @nestjs/mongoose version 6.1.2 fix the problem
initial we try to connect to database without username and password
MongooseModule.forRoot('mongodb://localhost/prospercare', { useCreateIndex: true,useNewUrlParser: true }),
for security reason we add username and password.
but after giving those details not able to connect to database using user name and password
MongooseModule.forRoot('mongodb://username:password@localhost/prospercare', { useCreateIndex: true,useNewUrlParser: true }),
getting error as MongoNetworkError: failed to connect to server [localhost] on first connect [MongoError: Not Authenticated.
[ ] 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.
When using a database (mongodb-memory-server) in a test case, the test passes but runs indefinitely with Jest throwing the warnings:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
--detectOpenHandles
supresses the warning but doesn't show any info.
The connection should be closed after all tests and the test case should complete after all tests pass, and there should be no async warning.
test-database.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
@Module({
imports: [
MongooseModule.forRootAsync({
useFactory: async () => {
const mongod = new MongoMemoryServer();
return {
uri: await mongod.getConnectionString(),
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
};
},
}),
],
})
export class TestDatabaseModule {}
test.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
@Injectable()
export class TestService {
constructor(
@InjectModel('test') private readonly test: Model<any>,
) {}
}
test.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { MongooseModule } from '@nestjs/mongoose';
import { TestDatabaseModule } from '../database/test-database.module';
import * as mongoose from 'mongoose';
import { TestService } from './test.service';
const testSchema = new mongoose.Schema({
test: String,
});
describe('TestService', () => {
let testingModule: TestingModule;
let service: TestService;
beforeEach(async () => {
testingModule = await Test.createTestingModule({
imports: [
TestDatabaseModule,
MongooseModule.forFeature([{ name: 'test', schema: testSchema }]),
],
providers: [TestService],
}).compile();
service = testingModule.get<TestService>(TestService);
});
afterEach(async () => {
await testingModule.close();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
jest.config.js
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
/** @type {jest.DefaultOptions} */
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// Respect "browser" field in package.json when resolving modules
// browser: false,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\mn\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: null,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,
// A path to a custom dependency extractor
// dependencyExtractor: null,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: null,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: null,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
moduleFileExtensions: [
"js",
"json",
"ts",
],
// A map from regular expressions to module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: null,
// Run tests from one or more projects
// projects: null,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: null,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
rootDir: 'src',
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
testRegex: '.spec.ts$',
// This option allows the use of a custom results processor
// testResultsProcessor: null,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.(t|j)s$": "ts-jest"
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: null,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
N/A
Nest version: 6.7.2
@nestjs/mongoose version: 6.1.2
For Tooling issues:
- Node version: v12.13.0
- Platform: Windows
Others:
[X] Documentation issue or request
How to run mongo raw queries? Can't find any docs for this
following the guide on the official nestjs docs, when trying to load a db connection string via a dotenv file, a error is thrown "URL malformed, cannot be parsed".
e.g.
dotenv file
db_connection = 'mongodb://localhost:27017/foo'
root.module
@ module({
modules: [
MongooseModule.forRoot(process.env.db_connection),
....
],
})
not sure if this is an implementation error from my part.
thanks,
Hi,
One of my schema uses the discriminators as elaborated in this blog http://thecodebarbarian.com/mongoose-4.8-embedded-discriminators.html.
When I use such a schema with nest-mongoose, I get the following error,
....\node_modules@nestjs\mongoose\mongoose.utils.js:4
return ${JSON.stringify(model)}Model
;
^
TypeError: Converting circular structure to JSON
I guess the code for generating model token will have to be changed since the schema JSON can not be serialized when there are discriminators.
Thanks.
[ ] 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.
when trying to insert a record in mongodb I get an unauthorized error, even following all documentation, my bank is on a server
[Nest] 3960 - 2019-2-26 17:36:11 [ExceptionsHandler] not authorized on teste
to execute command { find: "produtos", filter: {}, projection: {}, retur
nKey: false, showRecordId: false } +23089ms
MongoError: not authorized on teste to execute command { find: "produtos"
, filter: {}, projection: {}, returnKey: false, showRecordId: false }
manipulate the data without restrictions
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ProdutoModule } from './produto/produto.module';
import { MongooseModule } from '@nestjs/mongoose';
@module({
imports: [
ProdutoModule,
MongooseModule.forRoot('mongodb://kamino.mongodb.umbler.com:14702/teste', {useNewUrlParser: true})],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
the documentation on the connection with the mongodb is not detailed, very superficial
Nest version: 5.7.3
For Tooling issues:
- Node version: 10.15.1
- Platform: Windows
Others:
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I want to easily expose / exclude field.
First I started with @nestjs/typeorm but typeorm does not support references document for MongoDB.
So I come to mongoose but I don't understand how I can Exclude field with class-transformer..
A documentation / example explaining how to use "class-transformer" with @nestjs/mongoose
Nest version: 5.1.0
[ ] 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.
some out of date packages are having security vulnerabilities
braces and jest packages is out of date. Please update them. They are required by jest package.
npm should not indicate security vulnerabilities
npm install --save @nestjs/mongoose mongoose
DOS vuln removal
Nest version:5.8.0
For Tooling issues:
- Node version: 11.10
- Platform: Linux
ex:
export const NestedSchema = new Schema({
_id: false, // error TS2322: Type 'false' is not assignable to type 'Schema | SchemaTypeOpts<any> | SchemaType'.
first: String,
last: String
});
export const NestedSchema = new Schema({
name: NestedSchema
});
How to insert into a collection varying name ?
That is , My chat backend stores chat in seprarate collections in this format
id1_id2
for example
AA12_AA14 => member id 12 chatting with member id 14
AA15_AA16 => member id 15 chatting with member id 16
The tutorials only teaches to create a schema with a static name such such as Products
I need dynamic names
please help ?
[ ] Regression
[ ] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
We should refactor the forRoot method to not have the first param uri
. And make the URI non-optional in the MongooseModuleOptions. Then we could safe this if
statement. This would also have the advantage that the forRoot
method and the MongooseModuleAsyncOptions
have the same params. Which feels better for me.
None.
Better alignment of params. This would introduce breaking changes.
Nest version: 6.X
For Tooling issues:
- Node version: XX
- Platform:
Others:
[ ] Regression
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
The connection is created as a singleton
The connection options support scope
(https://docs.nestjs.com/fundamentals/injection-scopes) to be defined as per request.
I'd like to open an isolated connection on every HTTP requests.
Nest version: 6.1.2
[ ] 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.
MongooseModule.forRootAsync
doesn't connect to mongodb when we use useFactory
MongooseModule.forRootAsync
should be connect to mongodb when we use useFactory
MongooseModule.forRootAsync({
useFactory: () => ({
uri: 'mongodb://localhost/nest',
}),
})
"@nestjs/common": "^5.7.3",
"@nestjs/core": "^5.4.1",
"@nestjs/jwt": "^0.3.0",
"@nestjs/mongoose": "5.2.2",
"rxjs": "^6.2.2",
For Tooling issues:
- Node version: v11.9.0
- Platform: Linux
[x] Feature request
When using this package I would need to define my interface/class and my model for Mongoose in two different files or at least at two places instead of one.
This leads to ugly code and the need to keep them manually in sync.
Typegoose (https://github.com/szokodiakos/typegoose) allows me to define all the relevant stuff in just one class and additionally would allow me to use @nestjs/swagger
.
At the moment it is not possible to use typegoose, as far as I know, because there is no option to access the underlying mongoose connection of this module, which I would need to supply to Typegoose.
As nestjs is making heavy use of Typescript, integrating Typegoose would be a great idea imho.
Support for injecting the connection from the MongooseModule into Typegoose or direct support for Typegoose via this module.
Removing the need for a seperate interface when using mongoose models and making the life of Nest Developers easier.
[ ] Regression
[ ] Bug report
[X] Feature request
[X] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
I want to write a strongy modularized App that uses mongoose as a database. There is a collection, let's say Container, that is agnostic about where it is referenced. It might be in no other module in one or in multiple ones.
The can be an unknown amout of things that needs to be done when a Container is checked or removed. One module might want to protect a container from being removed, when it is still referenced, while another needs to remove an instance in itself. Or a module needs to realize that a field on a Container has been changed and change one on its own.
All this could be achieved with Schema hooks in vanilla mongoose. I just need to expose the Schema of Container before the call to get the Model of the Schema.
Unfortunately I do not see any point in time where I could be sure, to get a Schema, but where ot Model has been created of this. Would it be possible to expose this at a defined point during startup, so that other models could plant their hooks into the already existing Schema?
Thanks
Nest version: 6.2.2
Nest-mongoose: 6.1.2
For Tooling issues:
- Node version: 10.15.3
- Platform: Ubuntu 18.04
Others:
[X] Bug report
[X] Documentation issue or request
on Stack Overflow.
How do I enable debug mode to see mongo raw queries?
Trying to pass debug option like this
MongooseModule.forRootAsync({
useFactory: () => {uri: '', debug: true},
}),
doesn't give any effect
[ ] 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.
6.1.1 break sample 06
6.0.0 is ok
Yesterday I setup 6.1.0 is no problem.
I rem
[Nest] 4358 - 2019/04/16 δΈε12:35 [NestFactory] Starting Nest application...
[Nest] 4358 - 2019/04/16 δΈε12:35 [InstanceLoader] ApplicationModule dependencies initialized +48ms
[Nest] 4358 - 2019/04/16 δΈε12:35 [InstanceLoader] MongooseModule dependencies initialized +1ms
[Nest] 4358 - 2019/04/16 δΈε12:35 [ExceptionHandler] Nest can't resolve dependencies of the CatModel (?). Please make sure that the argument at index [0] is available in the MongooseModule context. +27ms
https://github.com/nestjs/nest/tree/master/sample/06-mongoose
yarn
yarn start
@nestjs/mongoose 6.1.1
For Tooling issues:
- Node version: XX
- Platform:
Others:
I tried the following and am getting products
when querying for either products
or templates
:
import { ProductsModule } from "./products/products.module";
import { TemplatesModule } from "./templates/templates.module";
@Module({
imports: [MongooseModule.forRoot(process.env.MONGODB_URL), ProductsModule, TemplatesModule],
})
export class ApplicationModule {}
@Module({
imports: [MongooseModule.forFeature([{ name: 'Product', schema: ProductSchema }])],
controllers: [ProductsController],
components: [ProductsService],
})
export class ProductsModule {}
@Module({
imports: [MongooseModule.forFeature([{ name: 'Template', schema: TemplateSchema }])],
controllers: [TemplatesController],
components: [TemplatesService],
})
export class TemplatesModule {}
Is it possible to use MongooseModule.forFeature()
multiple times within a program? I can't see anything in code which could cause this problem.
If I merge the 3 modules then I am getting templates
regardless if querying for products
or templates
.
import {ProductSchema} from "./products/product.schema";
import {ProductsController} from "./products/products.controller";
import {ProductsService} from "./products/products-service.component";
import {TemplateSchema} from "./templates/template.schema";
import {TemplatesController} from "./templates/templates.controller";
import {TemplatesService} from "./templates/templates.service";
@Module({
imports: [MongooseModule.forRoot(process.env.MONGODB_URL), MongooseModule.forFeature([{ name: 'Product', schema: ProductSchema }, { name: 'Template', schema: TemplateSchema }])],
controllers: [ProductsController, TemplatesController],
components: [ProductsService, TemplatesService],
})
export class ApplicationModule {}
Thanks in advance for any comments/pointers ;-)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.