Reputation: 45
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
Upvotes: 1
Views: 4332
Reputation: 493
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.
Upvotes: 5