mongoose#Connection TypeScript Examples

The following examples show how to use mongoose#Connection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: db-checker.ts    From server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks whether DB is Accessible by Checking the Mongoose Connection Status
 *
 * @param {Request} req - Express Request Object
 * @param {Response} res - Express Response Object
 * @param {NextFunction} next - Express Next Function
 */
function dbChecker(req: Request, res: Response, next: NextFunction): void {
  const mongoState = connection.readyState;
  if ([0, 2, 3].includes(mongoState)) {
    const result: IErrorResponse = {
      status: 500,
      errorname: `Database is ${STATES[mongoState]}`,
      message: 'Internal Server Error Related to Database',
    };
    res.status(500).json(result);
  } else {
    res.locals.dbcheck = true;
    next();
  }
}
Example #2
Source File: mongo.ts    From pancake-nft-api with GNU General Public License v3.0 6 votes vote down vote up
getConnection = async (): Promise<Connection> => {
  if (connection === null) {
    /* istanbul ignore next */
    const uri = process.env.MONGO_URI ?? "mongodb://localhost:27017/marketplace";
    connection = mongoose.createConnection(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      bufferCommands: false,
      bufferMaxEntries: 0,
    });

    await connection;
    connection.model("Collection", collectionSchema);
    connection.model("Token", tokenSchema);
    connection.model("Metadata", metadataSchema);
    connection.model("Attribute", attributeSchema);
  }

  return connection;
}
Example #3
Source File: database-connection.providers.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
describe('DatabaseConnectionProviders', () => {
  let conn: any;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [ConfigModule.forFeature(mongodbConfig)],
      providers: [...databaseConnectionProviders],
    }).compile();

    conn = module.get<Connection>(DATABASE_CONNECTION);
  });



  it('DATABASE_CONNECTION should be defined', () => {
    expect(conn).toBeDefined();
  });

  it('connect is called', () => {
    //expect(conn).toBeDefined();
    //expect(createConnection).toHaveBeenCalledTimes(1); // it is 2 here. why?
    expect(createConnection).toHaveBeenCalledWith("mongodb://localhost/blog", {
      // useNewUrlParser: true,
      // useUnifiedTopology: true,
      //see: https://mongoosejs.com/docs/deprecations.html#findandmodify
      // useFindAndModify: false
    });
  })

});
Example #4
Source File: database-connection.providers.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
databaseConnectionProviders = [
  {
    provide: DATABASE_CONNECTION,
    useFactory: (dbConfig: ConfigType<typeof mongodbConfig>): Connection => {
      const conn = createConnection(dbConfig.uri, {
        //useNewUrlParser: true,
        //useUnifiedTopology: true,
        //see: https://mongoosejs.com/docs/deprecations.html#findandmodify
        //useFindAndModify: false,
      });

      // conn.on('disconnect', () => {
      //   console.log('Disconnecting to MongoDB');
      // });

      return conn;
    },
    inject: [mongodbConfig.KEY],
  },
]
Example #5
Source File: database-models.providers.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
databaseModelsProviders = [
  {
    provide: POST_MODEL,
    useFactory: (connection: Connection) => createPostModel(connection),
    inject: [DATABASE_CONNECTION],
  },
  {
    provide: COMMENT_MODEL,
    useFactory: (connection: Connection) => createCommentModel(connection),
    inject: [DATABASE_CONNECTION],
  },
  {
    provide: USER_MODEL,
    useFactory: (connection: Connection) => createUserModel(connection),
    inject: [DATABASE_CONNECTION],
  },
]
Example #6
Source File: healthz.controller.ts    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
constructor(@InjectConnection() private readonly connection: Connection) {}
Example #7
Source File: index.ts    From vt-api with GNU Affero General Public License v3.0 5 votes vote down vote up
connection.on('connected', () => logger.log('Established connection to MongoDB.'));
Example #8
Source File: sanity.spec.ts    From pebula-node with MIT License 5 votes vote down vote up
describe('goosetyped-e2e', () => {
  let connection: Connection;

  beforeAll(async () => {
    connection = await createMongoConnection();
  });

  describe('e2e sanity', () => {

    @GtDocument()
    class TestClass extends GtModel() {

      @GtIndex({ sort: 'asc', options: { background: false } })
      @GtColumn() name: string;

      @GtVersionKey()
      version: number;

      @GtTimestampCreated()
      @GtIndex({ sort: 'desc', options: { background: false } })
      createDate: Date;

      @GtTimestampUpdated()
      @GtIndex({ sort: 'desc', options: { background: false } })
      updateDate: Date;

      @GtColumn() owner: string;
    }

    it('should create the collection', async () => {
      const collection = await TestClass.db.collection(TestClass.collection.collectionName);
      expect(collection).toBeDefined();
    });

  
    it('should create indexes for the collection', async () => {
      await TestClass.init();
      const indexInfo = await TestClass.collection.indexInformation();
      const indexes: Array<[string, -1 | 1]> = Object.values(indexInfo);

      expect(indexes.length).toBe(4);

      const expectedIndexes = [
        [['_id', 1]],
        [['name', 1]],
        [['createDate', -1]],
        [['updateDate', -1]],
      ];
      expect(expectedIndexes).toEqual(indexes);
    });

    it('should apply mixins', async () => {
      // let t = await TestClass.create({ name: 'test', owner: 'tester' });
      // t = await TestClass.findById(t.id);
      // expect(t.createDate).toBeInstanceOf(Date);
      // expect(t.updateDate).toBeInstanceOf(Date);
      // expect(t.name).toBe('test');
      // expect(t.owner).toBe('tester');
    });

  });
});
Example #9
Source File: mongo.ts    From pancake-nft-api with GNU General Public License v3.0 5 votes vote down vote up
connection: Connection | null = null
Example #10
Source File: tenancy-core.module.ts    From nestjs-tenancy with MIT License 5 votes vote down vote up
/**
     * Get the connection for the tenant
     *
     * @private
     * @static
     * @param {String} tenantId
     * @param {TenancyModuleOptions} moduleOptions
     * @param {ConnectionMap} connMap
     * @param {ModelDefinitionMap} modelDefMap
     * @returns {Promise<Connection>}
     * @memberof TenancyCoreModule
     */
    private static async getConnection(
        tenantId: string,
        moduleOptions: TenancyModuleOptions,
        connMap: ConnectionMap,
        modelDefMap: ModelDefinitionMap,
    ): Promise<Connection> {
        // Check if validator is set, if so call the `validate` method on it
        if (moduleOptions.validator) {
            await moduleOptions.validator(tenantId).validate();
        }

        // Check if tenantId exist in the connection map
        const exists = connMap.has(tenantId);

        // Return the connection if exist
        if (exists) {
            const connection = connMap.get(tenantId) as Connection;

            if (moduleOptions.forceCreateCollections) {
                // For transactional support the Models/Collections has exist in the
                // tenant database, otherwise it will throw error
                await Promise.all(
                    Object.entries(connection.models).map(([k, m]) => m.createCollection())
                );
            }

            return connection;
        }

        // Otherwise create a new connection
        const uri = await Promise.resolve(moduleOptions.uri(tenantId))
        const connection = createConnection(uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            ...moduleOptions.options(),
        });

        // Attach connection to the models passed in the map
        modelDefMap.forEach(async (definition: any) => {
            const { name, schema, collection } = definition;
            const modelCreated = connection.model(name, schema, collection);

            if (moduleOptions.forceCreateCollections) {
                // For transactional support the Models/Collections has exist in the
                // tenant database, otherwise it will throw error
                await modelCreated.createCollection();
            }
        });

        // Add the new connection to the map
        connMap.set(tenantId, connection);

        return connection;
    }
Example #11
Source File: tenancy-core.module.ts    From nestjs-tenancy with MIT License 5 votes vote down vote up
/**
     * Register for asynchronous modules
     *
     * @static
     * @param {TenancyModuleAsyncOptions} options
     * @returns {DynamicModule}
     * @memberof TenancyCoreModule
     */
    static registerAsync(options: TenancyModuleAsyncOptions): DynamicModule {

        /* Connection Map */
        const connectionMapProvider = this.createConnectionMapProvider();

        /* Model Definition Map */
        const modelDefinitionMapProvider = this.createModelDefinitionMapProvider();

        /* Tenant Context */
        const tenantContextProvider = this.createTenantContextProvider();

        /* Http Adaptor */
        const httpAdapterHost = this.createHttpAdapterProvider();

        /* Tenant Connection */
        const tenantConnectionProvider = {
            provide: TENANT_CONNECTION,
            useFactory: async (
                tenantId: string,
                moduleOptions: TenancyModuleOptions,
                connMap: ConnectionMap,
                modelDefMap: ModelDefinitionMap,
            ): Promise<Connection> => {
                return await this.getConnection(tenantId, moduleOptions, connMap, modelDefMap);
            },
            inject: [
                TENANT_CONTEXT,
                TENANT_MODULE_OPTIONS,
                CONNECTION_MAP,
                MODEL_DEFINITION_MAP,
            ]
        };

        /* Asyc providers */
        const asyncProviders = this.createAsyncProviders(options);

        const providers = [
            ...asyncProviders,
            tenantContextProvider,
            connectionMapProvider,
            modelDefinitionMapProvider,
            tenantConnectionProvider,
            httpAdapterHost,
        ];

        return {
            module: TenancyCoreModule,
            imports: options.imports,
            providers: providers,
            exports: providers
        };
    }
Example #12
Source File: tenancy-core.module.ts    From nestjs-tenancy with MIT License 5 votes vote down vote up
/**
     * Register for synchornous modules
     *
     * @static
     * @param {TenancyModuleOptions} options
     * @returns {DynamicModule}
     * @memberof TenancyCoreModule
     */
    static register(options: TenancyModuleOptions): DynamicModule {

        /* Module options */
        const tenancyModuleOptionsProvider = {
            provide: TENANT_MODULE_OPTIONS,
            useValue: { ...options },
        };

        /* Connection Map */
        const connectionMapProvider = this.createConnectionMapProvider();

        /* Model Definition Map */
        const modelDefinitionMapProvider = this.createModelDefinitionMapProvider();

        /* Tenant Context */
        const tenantContextProvider = this.createTenantContextProvider();

        /* Http Adaptor */
        const httpAdapterHost = this.createHttpAdapterProvider();

        /* Tenant Connection */
        const tenantConnectionProvider = {
            provide: TENANT_CONNECTION,
            useFactory: async (
                tenantId: string,
                moduleOptions: TenancyModuleOptions,
                connMap: ConnectionMap,
                modelDefMap: ModelDefinitionMap,
            ): Promise<Connection> => {
                return await this.getConnection(tenantId, moduleOptions, connMap, modelDefMap);
            },
            inject: [
                TENANT_CONTEXT,
                TENANT_MODULE_OPTIONS,
                CONNECTION_MAP,
                MODEL_DEFINITION_MAP,
            ],
        };

        const providers = [
            tenancyModuleOptionsProvider,
            tenantContextProvider,
            connectionMapProvider,
            modelDefinitionMapProvider,
            tenantConnectionProvider,
            httpAdapterHost,
        ];

        return {
            module: TenancyCoreModule,
            providers,
            exports: providers,
        };
    }
Example #13
Source File: tenancy.factory.ts    From nestjs-tenancy with MIT License 5 votes vote down vote up
createTenancyProviders = (definitions: ModelDefinition[]): Provider[] => {
    const providers: Provider[] = [];

    for (const definition of definitions) {
        // Extract the definition data
        const { name, schema, collection } = definition;

        providers.push({
            provide: getTenantModelDefinitionToken(name),
            useFactory: (
                modelDefinitionMap: ModelDefinitionMap,
                connectionMap: ConnectionMap,
            ) => {
                const exists = modelDefinitionMap.has(name);
                if (!exists) {
                    modelDefinitionMap.set(name, { ...definition });

                    connectionMap.forEach((connection: Connection) => {
                        connection.model(name, schema, collection);
                    });
                }
            },
            inject: [
                MODEL_DEFINITION_MAP,
                CONNECTION_MAP,
            ],
        });

        // Creating Models with connections attached
        providers.push({
            provide: getTenantModelToken(name),
            useFactory(tenantConnection: Connection) {
                return tenantConnection.models[name] || tenantConnection.model(name, schema, collection);
            },
            inject: [TENANT_CONNECTION],
        });
    }

    // Return the list of providers mapping
    return providers;
}
Example #14
Source File: user.model.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
createUserModel: (conn: Connection) => UserModel = (conn: Connection) =>
  conn.model<User>('User', UserSchema, 'users')
Example #15
Source File: post.model.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
createPostModel: (conn: Connection) => PostModel = (conn: Connection) =>
  conn.model<Post>('Post', PostSchema, 'posts')
Example #16
Source File: database-models.providers.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('DatabaseModelsProviders', () => {
  let conn: any;
  let userModel: any;
  let postModel: any;
  let commentModel: any;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ...databaseModelsProviders,

        {
          provide: DATABASE_CONNECTION,
          useValue: {
            model: jest
              .fn()
              .mockReturnValue({} as Model<User | Post | Comment>),
          },
        },
      ],
    }).compile();

    conn = module.get<Connection>(DATABASE_CONNECTION);
    userModel = module.get<UserModel>(USER_MODEL);
    postModel = module.get<PostModel>(POST_MODEL);
    commentModel = module.get<CommentModel>(COMMENT_MODEL);
  });

  it('DATABASE_CONNECTION should be defined', () => {
    expect(conn).toBeDefined();
  });

  it('USER_MODEL should be defined', () => {
    expect(userModel).toBeDefined();
  });

  it('POST_MODEL should be defined', () => {
    expect(postModel).toBeDefined();
  });

  it('COMMENT_MODEL should be defined', () => {
    expect(commentModel).toBeDefined();
  });
});
Example #17
Source File: database-connection.providers.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
jest.mock('mongoose', () => ({
    createConnection: jest.fn().mockImplementation(
      (uri:any, options:any)=>({} as any)
      ),
    Connection: jest.fn()
  }))
Example #18
Source File: comment.model.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
createCommentModel: (conn: Connection) => CommentModel = (
  connection: Connection,
) => connection.model<Comment>('Comment', CommentSchema, 'comments')
Example #19
Source File: app.service.ts    From nestjs-file-streaming with MIT License 5 votes vote down vote up
constructor(
    @InjectModel('fs.files') private readonly fileModel: Model<File>,
    @InjectConnection() private readonly connection: Connection,
  ) {
    this.bucket = new mongo.GridFSBucket(this.connection.db)
  }
Example #20
Source File: Database.ts    From void-wa with GNU General Public License v3.0 5 votes vote down vote up
public connection: Connection | undefined;
Example #21
Source File: index.ts    From vt-api with GNU Affero General Public License v3.0 5 votes vote down vote up
connection.on('disconnected', () => logger.warn('Lost connection to MongoDB.'));