Search code examples
angularmongodbmongodb-stitch

MongoDB Stitch in Angular 7 application


I am trying to add connectivity to MongoDB Stich in my Angular 7 application but app fails with error:

bson.browser.esm.js:453 Uncaught ReferenceError: global is not defined

I am using Angular 7.2.12 and have installed mongodb-stitch-browser-sdk v 4.3.2

I am using the code found on MongoDB website under DB Stitch application client setup.

import { Component, OnInit } from '@angular/core';
import { Stitch, RemoteMongoClient, AnonymousCredential} from 'mongodb-stitch-browser-sdk'

@Component({
  selector: 'app-alfabetisk',
  templateUrl: './alfabetisk.component.html',
  styleUrls: ['./alfabetisk.component.css']
})
export class AlfabetiskComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const client = Stitch.initializeDefaultAppClient('app-id');
  }
}

The app fails in ngOnInit() with the error:

bson.browser.esm.js:453 Uncaught ReferenceError: global is not defined at Module../node_modules/bson/dist/bson.browser.esm.js (bson.browser.esm.js:453) at webpack_require (bootstrap:78) at Module../node_modules/mongodb-stitch-core-sdk/dist/esm/index.js (index.js:1) at webpack_require (bootstrap:78) at Module../node_modules/mongodb-stitch-browser-core/dist/esm/index.js (index.js:1) at webpack_require (bootstrap:78) at Module../node_modules/mongodb-stitch-browser-sdk/dist/esm/index.js (index.js:1) at webpack_require (bootstrap:78) at Module../src/app/alfabetisk/alfabetisk.component.ts (main.js:95) at webpack_require (bootstrap:78)


Solution

  • Add this to polyfills.ts for Angular 6+

    /** Add global to window */
    (window as any).global = window;