MEAN Stack - 将云 MongoDB 连接到 Angular 应用程序?

MEAN Stack - Connect Cloud MongoDB to Angular Application?

我想我可能遗漏了一些东西,因为我 MongoDB 没怎么用过。

如何将我的 Angular 应用程序连接到我可以通过 Atlas 访问的 MongoDB 数据库?目前,我可以毫无问题地将应用程序连接到本地 MongoDB 数据库,但我找不到任何与将应用程序链接到实时数据库有关的信息。

server.js:

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';

// Models
import Invoice from './server/models/Invoice.model';

const app = express();
const router = express.Router();

app.use(cors());
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/[myDatabaseName]', {
  useNewUrlParser: true
})

const connection = mongoose.connection;

connection.once('open', _ => {
  console.log('MongoDB database connection established');
})

app.use('/', router);

router.route('/invoices').get((req, res) => {
  Invoice.find({}, (err, invoices) => {
    res.json(invoices);
  })
})

router.route('/invoices/:id').get((req, res) => {
  Invoice.findById(req.params.invoiceId, (err, invoice) => {
    res.json(invoice);
  })
})

router.route('/invoices').post((req, res) => {
  let newInvoice = new Invoice(req.body);
  newInvoice.save()
    .then(invoice => {
        res.status(200).send(invoice);
    })
    .catch(err => {
        res.status(400).send('Failed to save new invoice');
    })
  })

  router.route('/invoice/update/:id').post((req, res) => {
    Invoice.findById(req.params.id, (err, invoice => {
      if (!invoice) {
        return next(new Error('Unable to find invoice'));
      } else {
        invoice.save()
            .then(invoice => {
                res.json('Successfully updated invoice', invoice);
            })
            .catch(err => {
                res.status(400).send('Error updating invoice', err);
            })
      }
    }))
})

router.route('/invoices/delete/:id').get((req, res) => {
  Invoice.findByIdAndRemove({
    id: req.params.id
  }, (err, invoice) => {
    if (err) {
        res.json(err);
    } else {
        res.json('Successfully deleted invoice');
    }
  })
})

app.listen(4000, () => {
  console.log(`Express server running on port 4000`);
})

invoices.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, from } from 'rxjs';

import Invoice from '@app/interfaces/invoice.interface';
import { NotificationsService } from '@app/services/notifications/notifications.service';

@Injectable({
  providedIn: 'root'
})

export class InvoicesService {

  uri = 'http://localhost:4000';

  constructor(private notificationsService: NotificationsService, private http: HttpClient) {

  }

  getInvoices() {
    return this.http.get(`${this.uri}/invoices`);
  }

}

我已经在 mlab 中托管了我的 MongoDB,我正在使用下面的线路进行连接。检查这对你是否有用

const db = "mongodb://user:pass@dsxxxxx.mlab.com:port/poc"
mongoose.connect(db, err =>{
if(err){
    console.log('Error! '+ err)
}else{
    console.log('Connected to Mongodb')
}

})