Sails.js 1.x版本模型关联配置报错求助
解决Sails.js 1.x中Patients与Bookings模型关联的报错问题
看起来你在配置模型关联时遇到了两个典型问题,我帮你逐个拆解解决:
1. 先处理id属性的关联错误
报错提示:The attribute 'id' on the 'patients' model is an association but also specifies a type property.
这个问题的核心是你错误地把模型的主键id定义成了关联字段,并且额外添加了type属性——而Sails.js的关联字段是不需要手动指定type的,框架会自动根据关联类型推断。
修正步骤:
- 打开你的
api/models/Patients.js(注意Sails 1.x模型文件名推荐用单数,比如Patient.js,如果是复数也可以,但要和关联配置里的名称对应) - 如果你想让Patient和Booking建立关联,不要用
id作为关联字段,换一个合理的名称,比如:- 一对多关系(一个患者有多个预约):Patient模型里用
bookings作为集合关联,Booking模型里用patient作为模型关联 - 一对一关系:Patient模型里用
booking,Booking模型里用patient
- 一对多关系(一个患者有多个预约):Patient模型里用
正确的关联示例:
Patient模型(api/models/Patient.js)
module.exports = { attributes: { // 你的其他业务字段,比如name, phone等 name: { type: 'string', required: true }, phone: { type: 'string' }, // 关联字段:一个患者对应多个预约 bookings: { collection: 'booking', // 对应Booking模型的标识(小写单数) via: 'patient' // 对应Booking模型里指向Patient的字段名 } } };
Booking模型(api/models/Booking.js)
module.exports = { attributes: { // 你的其他业务字段,比如date, status等 date: { type: 'string', required: true }, status: { type: 'string', defaultsTo: 'pending' }, // 关联字段:一个预约属于一个患者 patient: { model: 'patient' // 对应Patient模型的标识(小写单数) } } };
- 重点:所有关联字段(不管是
model还是collection类型)都不要加type属性,完全交给Sails处理。
2. 解决数据存储标识无效的错误
报错提示:Invalid data store identity. No data store exist with that identity.
这个问题通常是模型里指定了不存在的数据存储配置,或者默认数据存储的配置有问题。
修正步骤:
- 检查你的Patient/Booking模型里是否有
datastore配置,比如:module.exports = { datastore: 'myCustomStore', // 这个标识在config/datastores.js里不存在 attributes: { /* ... */ } }; - 解决方式二选一:
- 直接删除模型里的
datastore配置,这样模型会自动使用config/datastores.js里的default数据存储 - 确保
config/datastores.js里有对应标识的配置,比如默认的配置应该是这样的(开发环境用磁盘适配器):// config/datastores.js module.exports.datastores = { default: { adapter: 'sails-disk' } // 如果有自定义存储,比如: // myCustomStore: { // adapter: 'sails-mysql', // url: 'mysql://user:password@localhost:3306/mydb' // } };
- 直接删除模型里的
- 如果你用了第三方适配器(比如MySQL、PostgreSQL),要确保已经安装对应的包,比如
npm install sails-mysql
最后验证
修正完以上两个问题后,重启你的Sails应用:
sails lift
如果没有其他配置问题,ORM应该能正常加载,模型关联也能正常工作了。
内容的提问来源于stack exchange,提问作者Levon Babayan
相关产品推荐
相关产品推荐

