在有角度的项目中使用猫鼬

mat*_*VIN 1 mongoose mongodb node.js angular

我尝试将 MongoDB 集成到我的项目 Angular 6 中。我想使用 ODM Mongoose。

npm 安装 mongoose --save

我创建了这个服务,它必须管理与数据库的连接

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 :}')})
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中启动应用程序时,出现以下错误:

SCRIPT5009:“全局”未定义

这个错误是什么意思?这是我必须导入猫鼬的方式吗?

预先感谢您的帮助

小智 5

Mongoose 是专门为 Node.js 设计的库,不能在浏览器环境中工作。为了能够连接数据库 - 您需要建立node.js后端服务器,例如express.js。然后您将能够通过 REST api 访问您的资源。

此外,您无法直接建立与数据库的连接,因为您需要以某种方式保护这些数据库内的数据。当您直接连接到数据库时 - 每个可以查看您的代码的人都将获得对数据的访问权限,这是严重的安全问题。