如何在Google Cloud上使用已安装的MongoDB。

huangapple go评论111阅读模式
英文:

How to use installed mongodb on google cloud

问题

我最近开发了一个使用Node.js的React应用程序,它依赖于MongoDB来存储数据。我刚刚在Google Compute Engine上安装了MongoDB并打开了端口27017。但是,我的问题是,如何将我的应用程序(我正在使用Mongoose)连接到虚拟机实例。

以下是本地主机(我的本地计算机)上的连接字符串,应该如何更改它:

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());

// 配置数据库
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// 连接到数据库
mongoose.connect(dbConfig.url, {
    useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true
}).then(() => {
    console.log("成功连接到数据库");
}).catch(err => {
    console.log('无法连接到数据库。现在退出...', err);
    process.exit();
});

// 要求路由
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("服务器正在监听端口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');

    // 创建新产品
    app.post('/products', products.create);

    // 检索所有产品
    app.get('/products', products.findAll);

    // 检索具有productId的单个产品
    app.get('/products/:productId', products.findOne);

    // 检索具有categoryId的产品
    app.get('/products/:categoryId', products.findWithCategoryId);

    // 使用productId更新产品
    app.put('/products/:productId', products.update);

    // 使用productId删除产品
    app.delete('/products/:productId', products.delete);
}

如何将本地主机数据库迁移到Google Compute Engine也是一个复杂的过程,它涉及备份和恢复数据库。您可以使用mongodumpmongorestore工具来执行这些操作。以下是大致的步骤:

  1. 在本地计算机上使用mongodump命令备份数据库:
mongodump --host localhost --port 27017 --out /path/to/backup/directory
  1. 将备份文件传输到Google Compute Engine实例。您可以使用scp或其他文件传输方法。

  2. 在Google Compute Engine实例上使用mongorestore命令还原数据库:

mongorestore --host localhost --port 27017 /path/to/backup/directory

请确保在Google Compute Engine上正确配置MongoDB,并使用正确的连接字符串。此外,还要确保Google Compute Engine实例上已经打开了MongoDB的端口(27017)。

英文:

I recently developed a react app with nodejs which depends on mongodb for its data. I have also just installed mongodb on Google Compute Engine and opened port 27017. However, my question is, how can i connect my application (I am using Mongoose) to the VM Instance.

Here is the connection string on localhost (my local machine), what should I change it to:

module.exports = {
    url: 'mongodb://localhost:27017/dapashirts'
}

Here is my server.js file:

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");
});

Here is a sample model:

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);

Here is a sample route:

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

How do i also transfer my localhost database to Google Compute Engine

答案1

得分: 1

最简单的方法是使用Mongo DB提供的数据库即服务(DaaS):
https://www.mongodb.com/cloud/atlas

英文:

The easiest way is to use a database as a service (daas) from Mongo DB:
https://www.mongodb.com/cloud/atlas

huangapple
  • 本文由 发表于 2020年1月7日 00:23:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定