Git Product home page Git Product logo

mongoose's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads Coverage Discord Backers on Open Collective Sponsors on Open Collective

Description

Mongoose module for Nest.

Installation

$ npm i --save @nestjs/mongoose mongoose

Quick Start

Overview & Tutorial

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

mongoose's People

Contributors

admosity avatar borntraegermarc avatar brunnerlivio avatar caucik avatar dependabot[bot] avatar dkokic avatar dotpack avatar dukezo avatar ginden avatar jiayisheji avatar jmcdo29 avatar kamilmysliwiec avatar kerrychen95 avatar kiwikern avatar lafeuil avatar ledniy avatar micalevisk avatar mohamedjkr avatar orgads avatar parzhitsky avatar piyush-kacha avatar pong420 avatar renovate-bot avatar renovate[bot] avatar silvelo avatar thiagomini avatar tony133 avatar warreee avatar wodcz avatar zaawee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose's Issues

Out of date Vulnerable dependencies fix

I'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.

Current behavior

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.

Expected behavior

npm should not indicate security vulnerabilities

Minimal reproduction of the problem with instructions

npm install --save @nestjs/mongoose mongoose

What is the motivation / use case for changing the behavior?

DOS vuln removal

Environment


Nest version:5.8.0
 
For Tooling issues:
- Node version: 11.10
- Platform:  Linux

Unable to auto index the collections in database.

I'm submitting a...


[ ] 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.

Current behavior

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.

Expected behavior

There should be indexes created in the database collection.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.0.0

 
For Tooling issues:
- Node version: 10.15.3  
- Platform:  Mac 

Others:

Problem using multiple collections

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 ;-)

How to use NestJS/mongoose with class-transformer

I'm submitting a...


[ ] 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.

Current behavior

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..

Expected behavior

A documentation / example explaining how to use "class-transformer" with @nestjs/mongoose

Environment


Nest version: 5.1.0

How to insert into a collection varying name ?

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 ?

Having a way to disconnect Database connection (or any services having a connection) properly when the app close

I'm submitting a...


[ ] 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.

Current behavior

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.

Expected behavior

During the app.close(), I would like my services connection to be closed properly.

Minimal reproduction of the problem with instructions

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...
  });
});

What is the motivation/use case for changing the behavior?

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.

Environment


Nest version: 6.7.2

 
For Tooling issues:
- Node version: 12.13.0
- Platform:  Linux and Mac

when using dotenv error - URL malformed, cannot be parsed

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,

[Discussion] Mongoose schema hooks w/ dependency injection

I'm submitting a...


[ ] 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.

Current behavior

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.

Include `repository` in package.json

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.

Align MongooseModuleOptions with MongooseModuleAsyncOptions

I'm submitting a...


[ ] 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.

Current behavior

Expected behavior

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.

Minimal reproduction of the problem with instructions

None.

What is the motivation / use case for changing the behavior?

Better alignment of params. This would introduce breaking changes.

Environment


Nest version: 6.X

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Mongoose - ability to use mongoose plugins in module imports declaration

I'm submitting a...


[ ] 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.

Current behavior

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.

Expected behavior

We should be able to use the plugins in @Module declarations.

Minimal reproduction of the problem with instructions

Mentioned in Current behavior section

What is the motivation / use case for changing the behavior?

To be able to use plugins for mongoose models, independent of whether the models are included in NestJS projects.

Environment


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:

i am facing this issue help me out of this

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

Missing "./dist"

I'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.

Current behavior

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?

Environment


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

Request scoped connections

I'm submitting a...


[ ] 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.

Current behavior

The connection is created as a singleton

Expected behavior

The connection options support scope (https://docs.nestjs.com/fundamentals/injection-scopes) to be defined as per request.

What is the motivation / use case for changing the behavior?

I'd like to open an isolated connection on every HTTP requests.

Environment


Nest version: 6.1.2

 

Typegoose not working with @nestjs/mongoose v5.0.0

Typegoose stop working after upgrade @nestjs/mongoose from version 4.0.0 to 5.0.0.

I'm submitting a...


[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.

Current behavior

When upgrade to version 5.0.0. I cannot make any query to my database.

Expected behavior

Should be working like version 4.0.0

Minimal reproduction of the problem with instructions

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
});

What is the motivation / use case for changing the behavior?

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.

Environment


Nest version: 5.0.1
 
For Tooling issues:
- Node version: 8.10.0
- Platform:  Windows 

Others: ...

Support to load mongoose module or plugin after getting configurations

I'm submitting a...


[ ] 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.

Current behavior

I have to call a configuration service before loading mongoose schema module or plugin, cause I need to use a key for encrypting.

Expected behavior

support to load mongoose module or plugin after getting configurations.

Minimal reproduction of the problem with instructions

  • test.schema.ts

      import { Document } from 'mongoose';
                
      export class TestSchema extends Document{
               readonly test: String;
      }

  • init.schema.ts
     export const initMongoosePlugin = () => {
        
          TestSchema.plugin(plugin, {
            fields: ['test'],
            secret: global['KEY'], // init it in main.ts
          });
        
     };
  • 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();

What is the motivation / use case for changing the behavior?

We have a configuration service to manager all configurations, so we need to call it for configurations to init our app.

Environment


Nest version: 6.9.0

 
For Tooling issues:
- Node version: v10.16.0
- Platform:  Mac / Windows

Others:

can't able to connect database using authentication

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.

Mongo raw queries

I'm submitting a...


[X] Documentation issue or request

How to run mongo raw queries? Can't find any docs for this

Warning in my terminal

WARNING: The useMongoClient option is no longer necessary in mongoose 5.x, please remove it

😄

How I can use discriminator

How I can use https://mongoosejs.com/docs/discriminators.html, I need to inject models with discriminator function


[ ] 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.

Current behavior

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Cant import mongoose.

mongoose

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"
  },

Typegoose Support

I'm submitting a...


[x] Feature request

Current behavior

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.

Expected behavior

Support for injecting the connection from the MongooseModule into Typegoose or direct support for Typegoose via this module.

What is the motivation / use case for changing the behavior?

Removing the need for a seperate interface when using mongoose models and making the life of Nest Developers easier.

Enable debug mode

I'm submitting a...


[X] Bug report
[X] Documentation issue or request
on Stack Overflow.

Current behavior

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

Inject model into schema for post hook

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.

MongooseModuleOptions should extend ConnectionOptions from @types/mongoose

I'm submitting a...


[ ] 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.

Current behavior

The actual Mongoose options passed to the library are not typesafe:

Expected behavior

We could make MongooseModuleOptions extend ConnectionOptions to provide typesafeness

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8c7f656341633979d006139e2a440b5d7575a5e5/types/mongoose/index.d.ts#L329

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Typesafeness

Environment


Nest version: 6

 
For Tooling issues:
- Node version: Any  
- Platform: Any 

Others:

Can't instance a model from mongoose after update from v4 to v6

I'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

6.1.1 break sample 06

I'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.

Current behavior

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

Expected behavior

Minimal reproduction of the problem with instructions

https://github.com/nestjs/nest/tree/master/sample/06-mongoose
yarn
yarn start

What is the motivation / use case for changing the behavior?

Environment


@nestjs/mongoose 6.1.1

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

MongooseModule forRootAsync doesn't connect to mongo

I'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.

Current behavior

MongooseModule.forRootAsync doesn't connect to mongodb when we use useFactory

Expected behavior

MongooseModule.forRootAsync should be connect to mongodb when we use useFactory

Minimal reproduction of the problem with instructions


MongooseModule.forRootAsync({
  useFactory: () => ({
    uri: 'mongodb://localhost/nest',
  }),
})

What is the motivation / use case for changing the behavior?

Environment


"@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


mongo error not authorized

I'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.

Current behavior

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 }

Expected behavior

manipulate the data without restrictions

Minimal reproduction of the problem with instructions

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 {}

What is the motivation / use case for changing the behavior?

the documentation on the connection with the mongodb is not detailed, very superficial

Environment


Nest version: 5.7.3

 
For Tooling issues:
- Node version: 10.15.1
- Platform:  Windows 

Others:

Add mocking possibility to nest/mongoose module

So after opening the issue in the wrong repository, here I'm again.

I'm submitting a...


[ ] 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.

Current behavior

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)

Expected behavior

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.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

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.

Environment

Plugins usage mongoose.model(name) not working

I'm submitting a...


[ ] 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.

@see Example

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,
    };
  }
}

App Module:

    MongooseModule.forRootAsync({
      useClass: MongoService,
    })

Schema

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;
    },
  },
});

Schema usage plugin mongoose-exists

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;
    },
  },
});

Environment


[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:

Unifying types

I'm submitting a...


[ ] 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.

Current behavior

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

Expected behavior

Can't we use something like typegoose but extended to everything? (Dto, Mongoose, Graphql, etc) just from different decorators?

Thank you!

MongooseModule Options doesn't work

I'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.

Current behavior

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.

Expected behavior

Enable MongooseModuleOptions in current version

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


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:

Error when schema discriminators are used on embedded array fields

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.

Jest: Connection not closing after test even with testingModule.close()

I'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.

Current behavior

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.

Expected behavior

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.

Minimal reproduction of the problem with instructions

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,
};

What is the motivation / use case for changing the behavior?

N/A

Environment


Nest version: 6.7.2
@nestjs/mongoose version: 6.1.2

 
For Tooling issues:
- Node version: v12.13.0  
- Platform:  Windows

Others:

Closing Connection after used

I'm submitting a...


[ ] 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.

Current behavior

  • test runner cannot exit gracefully,

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);
    });
  });

});

result:
image

Expected behavior

  • It should terminate gracefully.

Minimal reproduction of the problem with instructions

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();
    });
  })
});

result
image

What is the motivation / use case for changing the behavior?

  • to be able to close the db connection gracefully.
  • Maybe exposing this method this will be help or the module itself.

Environment


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

MongooseModule: same schema multiple collections

I'm submitting a...


[ ] 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.

Current behavior

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.

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Use the same schema for multiple collections.

Environment


Nest version: 4.5.9

 
For Tooling issues:
- Node version: v8.9.4
- Platform:  Windows

Others:

Feature Request: Allow non-default database connections

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.

Unit testing a service that uses @InjectConnection

I'm submitting a...

[ ] 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.

Current behavior

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.'

Expected behavior

I would like to be able to inject a mock of the connection object so that I can unit test the service.

Minimal reproduction of the problem with instructions

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);

What is the motivation / use case for changing the behavior?

I would like to be able to unit test this service.

Environment


Nest version: 5.4.0

 
For Tooling issues:
- Node version: 10.13.0  
- Platform:  Windows 

Others:

Initial Connection Error Handling

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?

can’t set property 'family' of MongooseModule options

I'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.

Current behavior

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)],

Expected behavior

be able to set property 'family' to 4

Minimal reproduction of the problem with instructions

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
}

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.10.14
@types/mongoose:  5.7.0

 
For Tooling issues:
- Node version: 12.9.1
- Platform:   Windows

Others:

Can't instance a model from mongoose after update from v4 to v6

Bug Report

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.

Input Code

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.

Expected behavior

Expecting that using mongoose.model() still can execute query, or if it is possible somehow to extract connection from app.module

Possible Solution

Environment


Nest version: 6.4.0


 
For Tooling issues:
- Node version: 8.13  
- Platform: Linux  

Others:
Mongoose verison: 5.6.3

hooks

I'm submitting a...


[ ] 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.

Current behavior

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

Environment


Nest version: 6.2.2
Nest-mongoose: 6.1.2
 
For Tooling issues:
- Node version: 10.15.3
- Platform:  Ubuntu 18.04

Others:

Is there a way to apply mongoose plugin after connection is created

I'm submitting a...


[ ] 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.

Current behavior

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().

Expected behavior

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.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Described in Current behavior

Environment


Nest version: 6.8.5

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

InjectModel from other module

I have two models imported to ApplicationModule:

  • AuthModule
  • UserModule
@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?

[QA] how to option nested schema _id:false?

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
});

please update to use db.model instead of mongoose.model

I'm submitting a...


[ ] 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.

Current behavior

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

Expected behavior

db command not hang

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

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:

Environment


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:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.