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

时间:2018-11-28 09:57:24

标签: angular mongodb mean-stack mean

我想我可能会缺少一些东西,因为我没有使用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`);
  }

}

1 个答案:

答案 0 :(得分:1)

我已经将我的MongoDB托管在mlab中,并且正在使用下面的代码进行连接。检查这是否对您有用

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')
}

})