Javascript 如何在谷歌云上使用已安装的mongodb
我最近用nodejs开发了一个react应用程序,它的数据依赖于mongodb。我还刚刚在谷歌计算引擎上安装了mongodb,并打开了27017端口。但是,我的问题是,如何将我的应用程序(我使用的是Mongoose)连接到VM实例 以下是localhost(我的本地计算机)上的连接字符串,我应该将其更改为什么:Javascript 如何在谷歌云上使用已安装的mongodb,javascript,node.js,reactjs,mongodb,mongoose,Javascript,Node.js,Reactjs,Mongodb,Mongoose,我最近用nodejs开发了一个react应用程序,它的数据依赖于mongodb。我还刚刚在谷歌计算引擎上安装了mongodb,并打开了27017端口。但是,我的问题是,如何将我的应用程序(我使用的是Mongoose)连接到VM实例 以下是localhost(我的本地计算机)上的连接字符串,我应该将其更改为什么: module.exports = { url: 'mongodb://localhost:27017/dapashirts' } 这是我的server.js文件: const
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):