我已经使用express generator成功生成并启动了一个nodejs应用程序。 我还创建了一个独立的(单个.js文件)mongoDB安装程序原型(使用mongoose-对我而言是第一次)。好
他们做得很好,但是当我将两者结合在一起时,我陷入了困境。 我认为我的错误是在module.exports语句中,但我不知道如何解决它。 有人可以帮我重写吗? nb我使用“ mongoose”:“〜5.3.16”,(...如果版本很重要?) 我的代码(我跳过了很长的部分): / bin / www(有关信息,可能不是问题):
var app = require('../app');
var debug = require('debug')('api-dfv2:server');
var http = require('http');
const loadConfig = require('../public/javascripts/loadConfig.js');
const config = loadConfig.getConfig();
var port = normalizePort(config.port);
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {(I skip...)
}
function onError(error) {(I skip here some code to handle errors+event listener for http server "listening" event...)
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var loadConfig = require('./public/javascripts/loadConfig.js');
var Conversation = require('./src/conversation');//declared but never read probably something wrong there
//the routers we need
var indexRouter = require('./routes/index');
var dfv2Router = require('./routes/dfv2');
//initiate express with moment
var app = express();
//link with moment module
app.locals.moment = require('moment');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');>>upgrade to pug
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//let's load the initial config (or defaults)
//it will exit if no credentials are provided.
loadConfig.setConfig();
/**
* map the routes
*/
app.use('/', indexRouter);
app.use('/dfv2', dfv2Router);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
在dfv2.js中,我收到了来自聊天系统的POST请求,我想将该内容存储在mongoDB中:
var express = require('express');
var router = express.Router();
const conversation = require('../src/conversation')
/* POST received from chat system */
router.post('/', function(req, res, next) {
dialogflowv2.getDFResponse(req.body)//I generate the answer to the chat
.then((DFanswer) => {
console.log(JSON.stringify(DFanswer));//not a nice way to debug but it works until that point
var currentConversation = new conversation;
console.log('test5');
currentConversation = {"moment": "test"};//I should write the full mapping with the body etc. here just to test one field
console.log(JSON.stringify(currentConversation));
currentConversation.save() // THIS IS WHERE IT GOES WRONG XXXXXX
//.then(function(tmp) {console.log("ok : ",tmp)})
//.catch(function() {console.log("DB error :")})
res.status(200).json(DFanswer);
})
.catch(err => res.status(400).json(JSON.stringify(err.message)))
})
module.exports = router;
有关信息,session.js
var mongoose = require('mongoose');
const server = '127.0.0.1:27017'; // DB SERVER
const database = 'test_laurent'; // DB NAME
mongoose.connect(`mongodb://${server}/${database}`,{useNewUrlParser: true})
.then(() => {
console.log('Database connection successful - system ready')
})
.catch(err => {
console.error('Database connection error')
})
//get mongoose to use the global promise library
mongoose.Promise = global.Promise;
var db = mongoose.connection;
//to bind error of DB with console
db.on('error',console.error.bind(console, 'MongoDB connection error:'));
let mySchema = new mongoose.Schema(
{
body: String,
sessionId: String,
moment: String
})
let conversation = db.model('conversation', mySchema);
module.exports = conversation;
结果是我的数据库什么也没收到。但是,如果我将对话.js的所有代码都当作一个独立的应用程序,它会很好地工作(POST>生成模式>构造对象> object.save>然后创建我的集合并在Compass中可见,因此数据库及其连接不是问题) 。 预先谢谢您,欢迎提供任何提示。
答案 0 :(得分:0)
转换是一个构造函数,但是在创建新对话时您不会调用它。
执行此操作:-
const currentConversation = new conversation({moment: test});
.save()也返回一个promise,因此您必须等待它,因此将.then.catch块附加到.save方法
currentConversation.save()
.then()
.catch()