Как использовать установленный mongodb в облаке Google - PullRequest
1 голос
/ 06 января 2020

Недавно я разработал приложение реагирования с nodejs, которое зависит от mongodb для его данных. Я также только что установил mongodb в Google Compute Engine и открыл порт 27017. Однако у меня вопрос: как я могу подключить свое приложение (я использую Mon goose) к экземпляру виртуальной машины.

Вот Строка подключения на локальном хосте (мой локальный компьютер), что я должен изменить на:

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

Вот мой сервер. 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);
}

Как мне также перенести мою базу данных localhost в Google Compute Engine

1 Ответ

1 голос
/ 06 января 2020

Самый простой способ - использовать базу данных в качестве службы (daas) с понедельника go БД: https://www.mongodb.com/cloud/atlas

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...