我在项目中使用带有mysql的node-orm2。我已经创建了数据库表,我可以在我的数据库中查询/查找数据。但是,当我想插入新数据时,没有任何反应 - 回调中没有错误,没有。
以下是相关代码:
模特课:
module.exports = function (orm, db) {
var Comment = db.define('comment', {
body: {type: 'text'}
});
};
模型文件夹中的Index.js:
var orm = require('orm');
var settings = require('../config/settings');
var connection = null;
function setup(db, cb) {
require('./comment')(orm, db);
return cb(null, db);
}
module.exports = function (cb) {
if (connection) return cb(null, connection);
orm.connect(settings.database, function (err, db) {
if (err) return cb(err);
connection = db;
db.settings.set('instance.returnAllErrors', true);
db.settings.set('connection.debug', true);
setup(db, cb);
});
};
控制器:
var orm = require('orm');
exports.create = function(req, res){
var testcomment = {};
testcomment.body = "test comment";
req.models.comment.create(testcomment, function (err, message) {
if (err) return console.log(err);
return res.send(200, message);
});
};
Environment.js
var path = require('path');
var express = require('express');
var settings = require('./settings');
var models = require('../models/');
var logger = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
module.exports = function (app) {
app.use(express.static(path.join(settings.path, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
app.use(function (req, res, next) {
models(function (err, db) {
if (err) return next(err);
req.models = db.models;
req.db = db;
return next();
});
})
};
Settings.js:
var path = require('path');
var settings = {
path : path.normalize(path.join(__dirname, '..')),
port : process.env.NODE_PORT || 3001,
database : {
protocol : "mysql",
host : "localhost",
port : "3306",
database : "taxidatabase",
user : "root",
password : "admin"
}
};
module.exports = settings;
我基本上遵循node-orm2中示例应用程序中的模式 - 但它不起作用。任何想法,为什么?
谢谢!
答案 0 :(得分:1)
在向表格添加任何内容之前,您需要在定义模型后至少一次同步 数据库以创建表格:
var models = require('../app/models/');
models(function (err, db) {
if (err) throw err;
db.sync(function (err) {
if (err) throw err;
console.log('Done!');
});
});
或者可能同步评论模型:
var orm = require('orm');
exports.create = function(req, res){
var testcomment = {};
testcomment.body = "test comment";
req.models.comment.create(testcomment, function (err, message) {
if (err) return console.log(err);
return res.send(200, message);
});
req.models.comment.sync(function (err) {
if (err) throw err;
console.log('Done!');
});
};