簡體   English   中英

使用MongoDB與Express api同時運行的Node JS應用

[英]Node JS app running at the same time as express api with MongoDB

我正在嘗試做的事情:我有一個小的Node應用程序向API發出請求,以獲取有關股票市場的數據,然后將數據保存到Mongo DB(已經制作並可以正常工作),我希望該數據庫能夠不斷運行。 接下來,我需要構建一個API,該API允許我的其他服務器/應用獲取該數據(尚未生成)。

我認為Express是一個不錯的選擇,盡管我知道還有其他選擇。 我從為MEAN堆棧應用程序構建的另一個API獲取此代碼,並且一直在進行故障排除。

我的主要問題是,大多數教程都展示了如何為MEAN,MERN和其他堆棧構建CRUD API。 我不確定如何構建該系統或Node應用程序是否可以按照我所描述的方式獨立運行。

目前,當我運行該應用程序時,我沒有收到任何錯誤,但是當我轉到端點時,我什么也沒收到。

當我剛開始時,我認為獨立的Node應用程序(其中的請求和寫入數據部分)可以與Express部分位於同一個文件中,但是現在我認為這樣做不可行,並將其拆分為單獨的文件。 我見過PM2和其他將節點應用程序變成后台服務的方法嗎?

不能完全確定,對此有一些澄清,以及一些有助於我的Express API端點為何不響應數據庫數據的幫助。 這是我的代碼。

獨立應用程序:

const request = require('request');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const d = new Date();
let day = d.getDay()
let hour = d.getHours();

const stockMomentSchema = new Schema({
    symbol: String,
    price: Number,
    size: Number,
    time: {type: Date, default: Date.now}
});

const StockMoment = mongoose.model('stockMoment', stockMomentSchema, 'stockPriceData');

mongoose.connect('mongodb://localhost:27017/stock-test')
    .then(() => {
        console.log('connected');
    })
    .catch(err => {
        console.error(err);
    });

function makeRequest() {
    if(day <= 1 || day >= 5) {
        if(hour >= 10 || hour <= 15) {
            getMarketData();
        }
    }
}

function getMarketData() {
    request({
        url: 'https://api.iextrading.com/1.0/tops/last',
        json: true
    }, (err, res, body) => {
        if(err) {
            return console.error(err);
        }

        for(let i = 0; i < body.length; i++) {
            const stockMoment = new StockMoment({
                symbol: body[i].symbol,
                price: body[i].price,
                size: body[i].size,
                time: body[i].time,
            });
            stockMoment.save((err) => {
                if(err) return handleError(err);
                console.log('Saved!', i);
            });
            console.log(body[i]);
        }
    });
}


makeRequest();

//setInterval(makeRequest, 5000);

server.js:

const express = require('express');
const path = require('path'); // Not sure if this is needed
const http = require('http');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();

const api = require('./api');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());

//app.use(express.static(path.join(__dirname, 'dist'))); // Not sure if this is needed

app.use('/api', api);

app.get('*', function(req, res) {
    res.status(404);
});

const port = process.env.PORT || '3000';
app.set('port', port);

const server = http.createServer(app);

server.listen('3000', function() {
    console.log('--------------------');
    console.log('Server running');
    console.log('You can view the server at http://localhost:3000');
    console.log('If you are running an Angular app on while using this server please use http://localhost:4200');
    console.log('--------------------');
});

庫存型號:

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

const StockSchema = mongoose.Schema({
    username: { type: String, unique: true, required: true },
    password: { type: String, required: true },
    email: {type: String, required: true},
    phoneNumber: {type: String, required: true},
    company: {type: String, required: true},
    about: {type: String, required: true},
    userType: {type: String, required: true}
});

StockSchema.plugin(uniqueValidator);

module.exports = mongoose.model('Stock', StockSchema);

api.js:

const express = require('express');
const router = express.Router();

const Stock = require('./stock.js');

router.get('/', function(req, res, err) {
    console.log('Hello world');
});


router.get('/stocks/:id', function(req, res, err) {
    console.log('Hello world');
    const stockData = {
        _id: false,
        symbol: true,
        price: true,
        size: true,
        time: true
    }
    Stock.findById(req.params.id, stockData, function(err, stock) {
        if(err) {
            res.send('No stocks found');
            console.log(err);
        } else {
            res.json(stock);
        }
    });
});

module.exports = router;

編輯:將mongoose.connect添加到server.js,但仍然無法正常工作

mongoose.connect('mongodb://localhost:27017/stock-test')
    .then((res) => {
        console.log('connected');
    })
    .catch(err => {
        console.error(err);
    });

編輯:這是工作更改的要點https://gist.github.com/drGrove/3e6699ded09f282e528a661fb41439e1

您的api正在拉入沒有與其關聯的信息的架構。 您應該分解StockMomentData,從api.js require它,並在id的get請求中使用它,而不是當前的stock模型。

由於您的貓鼬連接是在兩個“應用程序”之間共享的,因此您可以將其拉到db.js中,並且只需要在每個項目的加載時加載該文件即可(但這總是可以在以后執行)。

請注意,您確實需要在Model文件或api.js文件中建立連接,以便mongoose實際上連接至mongo數據庫

最初的答案:您的API服務器缺少通過mongoose與Mongo的連接。 您必須像在“獨立應用程序”中一樣進行連接呼叫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM