2014-11-25 44 views
1

我在我的項目中使用了node-orm2和mysql。我已經創建了數據庫表,並且我可以在數據庫中查詢/查找數據。但是,當我想要插入新數據時,什麼都沒有發生 - 回調中沒有錯誤,沒有任何反應。創建新模型不起作用 - 沒有錯誤

下面是相關代碼:

模型類:

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); 
     }); 
}; 

環境。 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; 

我基本上遵循在節點ORM2示例應用程序的模式 - 但它不工作。任何想法,爲什麼?

謝謝!

回答

1

之前添加任何表需要同步DB至少一次後,你才能創建表定義的車型:

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!'); 
    }); 
};