我最近使用nodejs开发了一个React应用,该应用的数据依赖于mongodb。我还刚刚在Google Compute Engine上安装了mongodb并打开了端口27017。但是,我的问题是,如何将我的应用程序(我正在使用Mongoose)连接到VM实例。
这里是本地主机(我的本地计算机)上的连接字符串,我应该将其更改为:
module.exports = {
url: 'mongodb://localhost:27017/dapashirts'
}
这是我的server.js文件:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Connecting to the database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
// Require routes
require('./routes/department.routes.js')(app);
require('./routes/category.routes.js')(app);
require('./routes/product.routes.js')(app);
require('./routes/order.routes.js')(app);
app.listen(3500, () => {
console.log("Server is listening on port 3500");
});
这里是示例模型:
const mongoose = require('mongoose');
const ProductSchema = mongoose.Schema({
category_id: {
type: [mongoose.Schema.Types.ObjectId],
required: true
},
name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
discounted_price: {type: Number, default: 0.00},
image: String,
image_2: String,
thumbnail: String,
display: { type: Number, min: 0, max: 3, default: 0 }
});
module.exports = mongoose.model('Product', ProductSchema);
这里是示例路线:
module.exports = (app) => {
const products = require('../controllers/product.controllers.js');
// Create a new product
app.post('/products', products.create);
// Retrieve all products
app.get('/products', products.findAll);
// Retrieve a single product with productId
app.get('/products/:productId', products.findOne);
// Retrieve a products with categoryId
app.get('/products/:categoryId', products.findWithCategoryId);
// Update a product with productId
app.put('/products/:productId', products.update);
// Delete a produt with productId
app.delete('/products/:productId', products.delete);
}
如何将本地主机数据库也转移到Google Compute Engine
最简单的方法是使用数据库作为Mongo DB中的服务(daas):https://www.mongodb.com/cloud/atlas