MEAN堆栈-将云MongoDB连接到Angular应用程序



我想我可能遗漏了一些东西,因为我很少使用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`);
})

发票服务.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')
}

})

相关内容

最新更新