Use mongoose in an angular project - node.js

I try to integrate MongoDB in my project angular 6. I want to use the ODM Mongoose.
npm install mongoose --save
I created this service which must manage the connection with the database
import { Injectable } from '#angular/core';
import { mongoose } from 'mongoose';
#Injectable()
export class BD {
private bd;
public test: string;
constructor(mongoose: mongoose){}
Test(){
mongoose('the url of the database')
this.bd = mongoose.connection;
this.bd.on('error', console.error.bind(console, 'error: impossible connection to the database'));
this.bd.once('open', ()=>{console.log('connected to the DB :}')})
}
}
When I launch the application in my browser I have this erreur:
SCRIPT5009: 'global' is not defined
What does this error mean?
Is this how I have to import mongoose?
Thank you in advance for your help

Mongoose is a library designed specially for node.js and won't work in the browser environment. In order to be able to connect the db - you need to establish node.js back-end server, for example express.js. Then you will be able access your resources through the REST api.
Also, you cannot establish connection to the database directly, because you need somehow secure the data inside those database. When you connecting to the database directly - everyone who can take a look at your code will gain acess to the data and this is serious security problem.

Related

NestJs for lambda with mongodb creating too many connections

We are using nestjs for lambda which connects with mongodb for data. We are using nestjs mongoose module. However on deployment for each invocation a new set of connection are made and the previous ones are not released.
We are using forRootAsync
MongooseModule.forRootAsync({
useClass: MongooseConfigService,
})
service looks like this:
#Injectable({ scope: Scope.REQUEST })
export class MongooseConfigService implements MongooseOptionsFactory {
constructor(#Inject(REQUEST) private readonly request: Request) {}
async createMongooseOptions(): Promise<MongooseModuleOptions> {
if (Buffer.isBuffer(this.request.body)) {
this.request.body = JSON.parse(this.request.body.toString());
}
const { db } = this.request.body;
console.log('connecting database', db);
return {
uri: process.env.MONGO_URL,
dbName: db || '',
};
}
}
I understand we need to reuse the same connection. We have achieved it in nodejs by simply checking if the connection already exists and if it does not connect again. Not sure how to achieve the same in nest.js
tried changing the scope of service to Scope.DEFAULT but that didn't help.
I would suggest that you make a connection proxy for MongoDB. Ever time a lambda gets invoked, it will open up a new connection to MongoDB. AWS generally provides a service that allows you to proxy requests through one connect, this is a common issue with RDS etc.
This may help you though: https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/
We were able to resolve the issue by using a durable provider. NestJs documentation we created a strategy at the root that would use a parameter coming in each request. NestJs would than call the connection module only when a new connection was required.
Note: When you use durable providers, Requests doesn't have all the parameters anymore and now only has the tenantId as per the example.

Angular Service with Azure Cosmos

I am really new to Angular. I am trying to create a service which i want to consume in my angular component. While doing so i am getting below error.
Below is my code which i am writing
import { Injectable } from '#angular/core';
import { HttpClient} from '#angular/common/http';
import { CosmosClient } from '#azure/cosmos';
import {Observable,of} from 'rxjs'
#Injectable({
providedIn: 'root'
})
export class ApiService {
databaseId='dbName';
containerId='Container Name';
constructor() { }
public async getProjects():Promise<Observable<any>>{
const endpoint = "https://AAAA.documents.azure.com:443/";
const key = "==";
const client = new CosmosClient({ endpoint, key });
const database = client.database(this.databaseId);
const container = database.container(this.containerId);
const querySpec = {query: "SELECT * from c where c.Category=\"Details\""};
const { resources:items } = await container.items.query(querySpec).fetchAll();
return of(items);
}
}
Any help is really appreciated.
There is an exception to every rule, but the use cases for connecting to a DB directly from a web browser are pretty close to zero. By doing so, you lose all fine grained control over what a user can do in your database and the only way to revoke access is to rotate your keys. You may not currently have anything in your database that is sensitive, but it is still considered bad practice.
For this reason, the CosmosDB library is compatible with NodeJS as a server-side framework. Whether or not it works with front end frameworks like Angular or React are incidental. There are some large changes in how Angular compiles projects in version 9, and it looks like the Cosmos client is not compatible with the new Ivy compiler.
You do have a couple options here.
(recommended) Use an API layer between your database and your front end. You can use Node to keep it within Javascript. If you are running on Azure, there are services like Azure Functions that can make this even easier to implement securely, or you can run it from the same App Service, VM, or whatever hosting solution you are using.
Disable the new Ivy compiler.You can do this by adding aot: false in your angular.json

Unable to connect to MongoDB via node js

I am writing a Node JS script to connect to MongoDB via mongoose library. When i tried to connect to MongoDB server i am getting MongoServerSelectionError: getaddrinfo ENOTFOUND. I tried in github, stackoerlow and websites suggested by google. But, nothing helpful. I created clusters in mongodb and everything works fine and i whitelisted the IP using 0.0.0.0\0.
Thanks in advance..!!!
This is the code I usually use for mongo connection.
import mongoose from 'mongoose';
import { Db } from 'mongodb';
import config from '../config';
export default async (): Promise<Db> => {
const connection = await mongoose.connect(config.databaseURL, { useNewUrlParser: true, useCreateIndex: true });
return connection.connection.db;
};
where config.databaseURL is mongo url with username and password.
Please try using your mongo url in mongo compass. That url should work with this code.

How to use postgres or SQL Server with nestjs

I am from .net background and few days back started using nestjs for one of my project.
I love the way nestjs built but few question here.
When using .net I can easily connect .net application with database by using some ORM like Ado.net, EF etc.
How do I connect nestjs with Postgres or SQL Server database?
Whatever will be the answer I would also like to know will that be suitable for enterprise applications?
Is there any reference site?
Thanks in advance
The docs show examples of how to conenct to a database using TypeORM and Sequilize, or you can roll your own dynamic module with custom providers if you want to use something else. There are a few packages around for knex, pg-promise, and massiveORM. These should all be more than suitable for enterprise applications, but if anything shows up as an issue, make sure to notify the owners of the repository.
Here is the basic structure I created to set up my current project with NestJS and PostgreSQL just in case this helps.
I added the following packages:
$ npm install --save knex objection objection-graphql pg
Created the nest database module and added this module to the "imports" and "exports" within the app.module.ts:
./src/database/database.module.ts
Then added the following files and folders:
./src/database/migrations
./src/database/models
./src/database/base.model.ts
./src/database/user.model.ts
./src/database/seeds
./src/database/migration.stub
./src/database/seed.stub
At the root level, I placed the knexfile.ts
import 'dotenv/config';
import Knex from 'knex';
import { knexSnakeCaseMappers } from 'objection';
module.exports = {
development: {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
directory: './src/database/migrations',
stub: './src/database/migration.stub',
},
seeds: {
directory: './src/database/seeds',
stub: './src/database/seed.stub'
},
...knexSnakeCaseMappers()
},
production: {
client: 'pg',
connectio: process.env.DATABASE_URL,
migrations: {
directory: __dirname + '/database/migrations',
},
seeds: {
directory: __dirname + '/database/seeds/production',
},
},
} as Knex.Config;
Then for each new Module, I called the model from the database folder
import { UserModel } from '../database/models/user.model'
That's it. Here you have connected PostgreSQL with NestJS.
As others have mentioned the NestJS manual is a well written resource for a detailed reference.
RON

node express postgres - why and how to connect to database using pg module?

I am super new to node express and postgres and wondering the following:
const pg=require('pg').native
const client=new pg.Clirnt('postgres ...')
what is const?
pg is used to create a client to connect to the Postgres database-correct?
If so
var db = new Sequelize('postgres://localhost:5432/mydb')
would work too or would I just have created a database without connecting it?
Why exactly do I need to connect at all-to do what?
Thanks a lot!
const is constant in javascript which was introduced in ES6 specification.
node-postgres is a client for PostgreSQL.
Sequelize is using node-postgres for working with PostgreSQL database, so yes, in the nutshell, it will act like node-postgres.
Imagine the warehouse, that's your database, where you have different shelves, that's your tables, to take or put different items into warehouse you need workers that will do your instructions like - INSERT someitem INTO items_shelf;. So worker is the client like Sequelize or node-postgres. The important part, warehouse should be open, otherwise, workers couldn't access to it, so your database should be turned on.
Hope I'm explained understandable enough.
what is const?
TLDR; variables that can't be re-assigned. scoped the same way as var. Part of es6.
pg is used to create a client to connect to the postgres database?
yes, note you need to do npm install --save pg as well as npm install --save sequelize. the save flag adds the packages to the package.json file for your convenience.
would I just have created a database without connecting it?
That bit of code should instantiate a connector - you haven't modified the database, and you also don't really know if the connection works yet.
why exactly do I need to connect at all?
The pg library looks to use a connection pool; this means you set it up once, and then you use it repeatedly as desired and it handles the connections for you. You connect now so you can run queries against the database later.
This snippet of code connects to a postgres instance running locally on my machine, and tests that it can connect - per the docs
const Sequelize = require('sequelize');
var sequelize = new Sequelize('postgres://localhost:5432/postgres');
sequelize.authenticate().then(() => {
console.log('yay');
}).catch((e) => {
console.log('nooo', e);
});

Resources