gpt4 book ai didi

javascript - 如何在谷歌云上使用已安装的 mongodb

转载 作者:行者123 更新时间:2023-11-30 18:59:55 26 4
gpt4 key购买 nike

我最近用 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

关于javascript - 如何在谷歌云上使用已安装的 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59615545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com