Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mongodb-stitch library in Angular 4

Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.

There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using @types) to no avail.

Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.

like image 759
trashvin Avatar asked Jun 12 '26 15:06

trashvin


2 Answers

The other answer suggests instantiating a new instance of StitchClient which is something that MongoDB have explicitly advised against in the Official API Documentation - and with reason, since there is a factory method available for that purpose. So, (after installing mongodb-stitch), the following code would help you get started in component.ts

import { Component, OnInit } from "@angular/core";
import { StitchClientFactory } from "mongodb-stitch";

let appId = 'authapp-****';

@Component({
selector: "app-mongo-auth",
templateUrl: "./mongo-auth.component.html",
styleUrls: ["./mongo-auth.component.css"]
})

export class MongoAuthComponent implements OnInit {

mClient;

ngOnInit() {
  this.mClient = StitchClientFactory.create(appId);
}

And you can then use this for whatever purpose you want, such as for implementing sign-in with Google

gLogin(){
this.mClient.then(stitchClient => {
  stitchClient.authenticate("google");
})
like image 165
theRealTraveller Avatar answered Jun 14 '26 08:06

theRealTraveller


not sure whether the question is still relevant considering it was asked two months ago but anyway...

As you pointed out you can use npm install --save mongodb-stitch to install the package and since there is no TS binding you can declare the stitch library as any

For example:

    declare var stitch: any;

    export class MyService implements OnInit {
    db;

    client;

    ngOnInit() {
        this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
        this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
        this.client.login();
    }

    save() {
        this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
    }

  }
like image 31
neta Avatar answered Jun 14 '26 10:06

neta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!