我正在构建一个小型Webapp。我使用MongoDB检索和存储我的数据,目前一切运行正常,但现在我想在线托管我的应用程序。
我知道如何在Heroku上部署我的脚本,但是我不知道它应如何与MongoDB一起使用,也许将MongoDB添加到我的应用程序要求中?
我进行了一些研究,发现了有关Mlab的信息,其中有一个Heroku插件,但遗憾的是Mlab即将迁移到Atlas
答案 0 :(得分:2)
(编辑,只是说您添加了要迁移的mlab,AWS还提供了与您说的Atlas上的mlab相同的沙箱选项,您也可以在本地安装并将其添加到您的settings.py中)< / p>
我使用此网站制作了一个沙盒免费 CDN数据库https://mlab.com/
在从CDN使用数据库的地方坚持这一行,这样我们甚至不需要在系统上安装它!
//这是我们的MongoDB数据库,请将其更改为CLOUD MONGO链接const dbRoute =“ mongodb:// *****:******@******.mlab.com:***** / *********”; >
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const logger = require("morgan");
const Data = require("./data");
const API_PORT = 3001;
const app = express();
const router = express.Router();
// this is our MongoDB database, change this to CLOUD MONGO link
const dbRoute = "mongodb://*****:******@******.mlab.com:*****/*********";
// connects our back end code with the database
mongoose.connect(
dbRoute,
{ useNewUrlParser: true }
);
let db = mongoose.connection;
db.once("open", () => console.log("connected to the database"));
// checks if connection with the database is successful
db.on("error", console.error.bind(console, "MongoDB connection error:"));
// (optional) only made for logging and
// bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger("dev"));
// this is our get method
// this method fetches all available data in our database
router.get("/getData", (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
// this is our update method
// this method overwrites existing data in our database
router.post("/updateData", (req, res) => {
const { id, update } = req.body;
Data.findOneAndUpdate(id, update, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
// this is our delete method
// this method removes existing data in our database
router.delete("/deleteData", (req, res) => {
const { id } = req.body;
Data.findOneAndDelete(id, err => {
if (err) return res.send(err);
return res.json({ success: true });
});
});
// this is our create methid
// this method adds new data in our database
router.post("/putData", (req, res) => {
let data = new Data();
const { id, message } = req.body;
if ((!id && id !== 0) || !message) {
return res.json({
success: false,
error: "INVALID INPUTS"
});
}
data.message = message;
data.id = id;
data.save(err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
// append /api for our http requests
app.use("/api", router);
// launch our backend into a port
app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));