如何用mongoDb实现Express?

我正在使用ErikRas的启动器在React,Redux,Express和Socket io中构build一个Web站点: https : //github.com/erikras/react-redux-universal-hot-example

对我来说,这看起来很疯狂:这么多的教程反应和redux。 不想说如何实现MongoDb。 我希望答案对其他人也有用。 事实上,我们可以在网上find的所有初学者都避免谈论和提供数据存储的例证。 也许是因为它太复杂了。 我不知道。 所以…我试图添加MongoDb。 这些教程显示了不同的方式,但始终以纯粹的node.js和express来表示,并且通常具有非常简单的设置。 但是首发的api根本不容易,我迷路了! 我不知道是否必须在api.js或server.js或…中连接它,我非常迷惑!

我设置了MongoDb,它工作正常。 我已经通过terminal收取了一些数据。 然后,在api.js中,我添加了一些行(在下面的代码中注释):

import express from 'express'; import session from 'express-session'; import bodyParser from 'body-parser'; import config from '../src/config'; import * as actions from './actions/index'; import {mapUrl} from 'utils/url.js'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; // --------------- New Code var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/nodetest1'); // -------------------------------------- const pretty = new PrettyError(); const app = express(); const server = new http.Server(app); const io = new SocketIo(server); io.path('/ws'); app.use(session({ secret: 'react and redux rule!!!!', resave: false, saveUninitialized: false, cookie: { maxAge: 60000 } })); app.use(bodyParser.json()); app.use((req, res) => { const splittedUrlPath = req.url.split('?')[0].split('/').slice(1); const {action, params} = mapUrl(actions, splittedUrlPath); if (action) { action(req, params) .then((result) => { if (result instanceof Function) { result(res); } else { res.json(result); } }, (reason) => { if (reason && reason.redirect) { res.redirect(reason.redirect); } else { console.error('API ERROR:', pretty.render(reason)); res.status(reason.status || 500).json(reason); } }); } else { res.status(404).end('NOT FOUND'); } }); // -------------------> New code -> 'II part' app.use(function(req,res,next){ req.db = db; next(); }); // -------------------------------- const bufferSize = 100; const messageBuffer = new Array(bufferSize); let messageIndex = 0; if (config.apiPort) { const runnable = app.listen(config.apiPort, (err) => { if (err) { console.error(err); } console.info('----\n==> 🌎 API is running on port %s', config.apiPort); console.info('==> 💻 Send requests to http://%s:%s', config.apiHost, config.apiPort); }); io.on('connection', (socket) => { socket.emit('news', {msg: `'Hello World!' from server`}); socket.on('history', () => { for (let index = 0; index < bufferSize; index++) { const msgNo = (messageIndex + index) % bufferSize; const msg = messageBuffer[msgNo]; if (msg) { socket.emit('msg', msg); } } }); socket.on('msg', (data) => { data.id = messageIndex; messageBuffer[messageIndex % bufferSize] = data; messageIndex++; io.emit('msg', data); }); }); io.listen(runnable); } else { console.error('==> ERROR: No PORT environment variable has been specified'); } 

……但是在terminal上马上给出了一个错误:

 proxy error { Error: connect ECONNREFUSED 127.0.0.1:3030 at Object.exports._errnoException (until.js953:11) at exports._exceptionWithHostPort (until.js:976:20) at TCPConnectWrap.afterConnect [as oncomplete ] (net.js:1080:14) code: 'ECONNREFUSED' errno: 'ECONNREFUSED' syscall: 'connect' address: '127.0.0.1' port: 3030 } 

在哪里以及如何实现MongoDb? 为什么即使当我添加的代码的第二部分不存在时,我也得到了错误? 任何有用的文档的链接?

先谢谢你!

所以,我在这里提供一个解决scheme。 我会尽量留下一个我想find的答案。

目前,我刚刚在Mongo数据库中写入。 但是还有很多工作要做。 我不确定我用它的方式是最好的performance。 因此,随时改进它,并形成一个完整的答案。

所以,在这里,我如何使用Express和Socket.io来使用MongoDb。 我正在从Erik Ras的样板构build我的网站

 https://github.com/erikras/react-redux-universal-hot-example 

在您的计算机上安装MongoDb。 它会在Mongo中安装C:\我做了两次,第二次安装在Porgrams中。

在名为api的文件夹中创build一个名为“data”的新文件夹。

然后使用MongoDb文件夹内的terminal导航并findbin。 从那里,数字文件夹的path:

 mongod --dbpath c:\nameofthefolderproject\api\data 

Mongo初始化数据存储(需要一些时间),启动并等待连接。

使用项目根目录中的terminal进行导航并安装mongoose:

 npm install mongoose 

然后打开文件名称\ project \ api \ api.js文件名里有import mongoose:

 import mongoose from 'mongoose'; 

并在import后添加:

 var mongoURI = "mongodb://localhost/nameofyourproject"; var db = mongoose.connect(mongoURI, function(err){ if(err){ console.log(err); }else{ console.log('Finally connected!!!'); } }); 

你应该在terminal收回信息。

在名为nameofthefolderproject \ api \ models的api文件夹中创build一个文件夹

在里面创build文件名称的文件夹\ project \ api \ models \ members.js

创build一个mongoose模式。 如果你不知道,请看文档来理解它。

var mongoose = require('mongoose');

 var membersSchema = mongoose.Schema({ pseudo:{ type: String, required: true }, email:{ type: String, required: true }, date:{ type: Date, default: Date.now } }); 

var Members = module.exports = mongoose.model('members',membersSchema);

创build文件:nameofthefolderproject \ api \ models \ index.js并写入以下内容。 在这里,您将收集所有准备使用的模型。

 export members from './members'; 

当api调用动作时,将模型传递给函数。

 app.use(bodyParser.json()); app.use((req, res) => { const splittedUrlPath = req.url.split('?')[0].split('/').slice(1); const {action, params} = mapUrl(actions, splittedUrlPath); // it calls the right action passing also the mongoose schemas (models) if (action) { action(req, params, models) etc etc... 

现在进入服务器调用的动作。 在我的情况下:nameofthefolderproject \ api \ actions \ addMember现在可以使用该模型进行注册。 在我的情况下:

 export default function addMember(req, err, models) { // this is the function called by the api. I passed all the models of mongoose. return new Promise((resolve, reject) => { // charge the data received from the form in a variable var data = req.body; // extract the mongoose model I interested about. var Members = models.members; // initialise the mongoose schema and connect the data received to the schema var newMember = new Members({pseudo:data.pseudo, email:data.email}); // In this way I can register the data in mongodb data store newMember.save(function(err, data){ // verify if there is an error, and confirm eventually the success if(err){ throw err; reject(); } resolve(); }); }); } 

如果在接下来的几天我会有时间的话,我会把剩下的时间发展起来。

请享用。

马克斯

感谢您的快速回答。 实际上,server.js使用的是端口3030.但是MongoDb使用的是27017端口。这样我就不明白为什么两者不能一起工作。 正如我所说:

 // --------------- New Code var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/nodetest1'); // -------------------------------------- 

…它变得疯狂:-)

我用“express”:“^ 4.13.3”,节点是v 6.2.0