Sails v1.0:在 mongo 中使用自定义主键时出错 [英] Sails v1.0: error while using custom primary key with mongo
问题描述
我正在试用 SailsJS (v1.0.0-32) 的测试版,但在配置自定义 ID 时遇到了一些问题.波纹管你会发现我当前的配置:
I'm giving a try to the beta version of SailsJS (v1.0.0-32) and I'm having some issues while configuring a custom id. Bellow you'll find my current configuration:
modelExample.js
module.exports = {
attributes: {
id:{
type: 'string',
columnName: '_id'
},
attr: {
type: 'number'
}
}
}
模型配置 config/models.js
attributes: {
createdAt: { type: 'number', autoCreatedAt: true, },
updatedAt: { type: 'number', autoUpdatedAt: true, },
id: { type: 'string', columnName: '_id' },
}
尝试插入的元素:
{id:"600000", attr:40}
我在尝试创建包含在尝试创建的元素中的属性id"的记录时遇到的错误
:
The error
I get when trying to create a record with an attribute "id" included in the element trying to be created:
AdapterError: Unexpected error from database adapter: Invalid primary key value provided for `id`. Cannot interpret `600000` as a Mongo id.
(Usually, this is the result of a bug in application logic.)
似乎 mongo 不喜欢将字符串 600000
作为 id
,但我不确定我是否误解了与 mongo 中的 id 相关的内容.在旧版本的风帆中,我从来没有遇到过这个问题,因为 id 覆盖很简单.
Seems that mongo does not like the string 600000
as an id
, but I'm not sure if maybe I'm misunderstanding something related to ids in mongo. In the old version of sails, I never had this issue since the id override was straightforward.
更多信息,sails-mongo 适配器版本为:"sails-mongo": "^1.0.0-5"
For more information, the sails-mongo adapter version is: "sails-mongo": "^1.0.0-5"
推荐答案
为了在 Sails 1.0 中将非 ObjectID 主键与 sails-mongo
一起使用,您必须设置 dontUseObjectIds:在您的模型中为 true
,例如:
In order to use non-ObjectID primary keys with sails-mongo
in Sails 1.0, you have to set dontUseObjectIds: true
in your model, for example:
// api/models/User.js
module.exports = {
dontUseObjectIds: true,
attributes: {
id: { type: 'number', columnName: '_id' }, // <-- still need to set `columnName`!
name: { type: 'string' },
...etc...
}
}
这是从 sails-mongo
v1.0.0-7 开始实现的.
This is implemented as of sails-mongo
v1.0.0-7.
这篇关于Sails v1.0:在 mongo 中使用自定义主键时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!