尝试从Sails.js控制器调用模型上的.create()
时出现以下错误。
这是我的模型,TemperatureReading.js:
module.exports = {
connection: 'mainDatabase',
tableName: 'TemperatureReading',
attributes: {
id: {
columnName: 'id',
type: 'integer',
minLength: 1,
primaryKey: true,
unique: true
},
deviceId: {
columnName: 'deviceId',
type: 'integer',
minLength: 1,
},
temperatureReading: {
columnName: 'temperatureReading',
type: 'string',
max: 150,
required: true
},
dateRecorded: {
columnName: 'dateRecorded',
type: 'string',
},
}
};
routes.js:
module.exports.routes = {
'get /enterSensorReading': 'MainController.getSensorReading'
};
MainController.getSensorReading:
getSensorReading: function (request, response) {
var temperatureReading = request.param('temperatureReading');
var date = new Date();
var dateRecorded = date.getDate() + "/"
+ (date.getMonth()+1) + "/"
+ date.getFullYear() + " "
+ date.getHours() + ":"
+ date.getMinutes() + ":"
+ date.getSeconds();
console.log(temperatureReading);
TemperatureReading.create({temperatureReading: temperatureReading, dateRecorded: dateRecorded}).exec(function(err, createdReading) {
if(err) {
response.send(err);
} else {
console.log('Created reading');
}
});
}
connections.js
module.exports.connections = {
mainDatabase: {
adapter: 'sails-mysql',
host: '127.0.0.1',
port: 3306,
user: 'myUser',
password: 'myPW',
database: 'MAIN'
}
};
最后,我的数据库结构:
TemperatureReading
------------------
id int(5) PK
deviceId int(5)
temperatureReading varchar(255)
date varchar(255)
关于出了什么问题的任何想法?
答案 0 :(得分:1)
数据库结构应该是这样的:
mysql> describe TemperatureReading;
+--------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| deviceId | int(11) | YES | | NULL | |
| temperatureReading | varchar(255) | YES | | NULL | |
| dateRecorded | varchar(255) | YES | | NULL | |
| createdAt | datetime | YES | | NULL | |
| updatedAt | datetime | YES | | NULL | |
+--------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
应该是 dateRecorded ,而不仅仅是日期
如果是新应用并且您是从头开始创建表格,请在模型中添加"migrate": "drop"
。这将自动为您创建表格。请务必在下次提起服务器时删除此行。如果这不能解决问题,那么我不会发现代码有任何问题。我测试过,它在我的系统上运行得很好。可能有些东西搞砸了你的sails-mysql适配器。如果修复数据库结构无法解决问题,请尝试使用
npm uninstall sails-mysql
npm cache clear
npm install sails-mysql
更严格的方式是:
rm -Rf node_modules
npm cache clear
npm install
如果这解决了您所面临的问题,请告诉我