【发布时间】:2015-02-27 21:38:02
【问题描述】:
我正在尝试使用具有关联的模型。我有两个模型定义如下:
User.js
module.exports = {schema: true, attributes: {
userId: {
autoIncrement: true,
type: integer,
primaryKey: true,
},
userId: {type: integer},
email: {type:string, size:200},
addressId: {
model:UserAddress
}
}
Address.js
module.exports = {schema: true, attributes: {
addressId: {
autoIncrement: true,
type:integer,
primaryKey:true
},
userId: {type:integer},
address: {type:string, size:250}
}
到目前为止,我能够通过将以下 JSON POST 到
来在两个模型中创建记录http://localhost:1337/user/
{
"userName": "John",
"userId": "3",
"email":"john@hotmail.com",
"addressId": {
"userId": "3",
"address": "123 abc street"
}
}
我能够使用带有此 URL 的 PUT 更新两条记录:
http://localhost:1337/user/update/1和下面的 JSON,请注意,在这种情况下,我在嵌套的 JSON 中添加了 addressId。
{
"userName": "John",
"userId": "3",
"accountLogin":"john@hotmail.com",
"addressId": {
"addressId":1,
"userId": "3",
"streetAddress": "123 abc street"
}
}
但是,当我第一次在 User 表中创建一条没有地址的记录,后来又想添加它时,我没有运气让它工作。我所做的是对http://localhost:1337/user/update/1 使用PUT 和以下JSON,因为地址是新的,所以没有addressId。
{
"userName": "John Doe",
"accountLogin":"john@hotmail.com",
"addressId": {
"userId": "3",
"streetAddress": "123 abc street"
}
}
有没有办法做我在 Sails.js 中尝试做的事情?我可以发布到http://localhost:1337/address 来创建新记录,但我想让我的 API 保持一致是可能的。更严重的问题是,当上面的 JSON 被发送时,它崩溃了后端。在我看来,用户可以通过发送无效的 JSON 轻松地使后端崩溃,我将如何保护后端免受这种崩溃?
【问题讨论】:
-
我只是在考虑您的问题,并想出了一件事可能有助于进一步调查:您使用的是哪个适配器,您是否尝试使用另一个适配器。
-
我正在使用 mysql。错误消息看起来与适配器无关,它说:“/jzj/node_modules/sails/node_modules/waterline/lib/waterline/utils/nestedOperations/update.js:532 this.create(record).exec(function(err , val) { ^ TypeError: Object #
-
您可以在使用水线默认主键时尝试吗?而且您也没有完全使用一对一关联,因为您的地址中没有关联反射,因为您的“userId”字段代表一个整数它应该是一个合适的“用户”
userId : { model : user } -
您的
update代码是什么样的?您使用的是User.find,还是使用User.update?
标签: sails.js waterline model-associations