gpt4 book ai didi

javascript - 如何使用环回和 mongodb 将嵌套对象中的属性转换为 ObjectId?

转载 作者:可可西里 更新时间:2023-11-01 10:43:21 25 4
gpt4 key购买 nike

假设我有以下模型定义:

{
"name": "Report",
"idInjection": true,
"trackChanges": true,
"mongodb": {
"collection": "report"
},
"properties": {
"resource" : {"type": "String"},
"date" : {"type": "Date"},
"people" : [ {
// Here's where I like to have an id property.
"role" : {"type": "String"},
"hours" : {"type": "Number"}
} ],
"name" : {"type": "String"}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}

现在我想在 people 数组中的每个对象中都有 id 属性(可以像 report.people[0].id 一样访问)并且它应该在插入和更新时被转换到 ObjectId。但是好吧,loopback 没有 ObjectId 类型,唯一的方法似乎是使用关系,但是外键应该如何呢?

有没有办法在插入和更新时将 id 属性强制转换为 ObjectId?

更新:

我尝试使用 embedsMany,但没有转换 id:

这是我的 report.json:

{
"name": "Report",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"people" : {
"type": "embedsMany",
"model": "ReportPerson",
"options": {
"validate": true,
"autoId": false
}
}
},
"acls": [],
"methods": []
}

这是我的 report-person.json:

{
"name": "ReportPerson",
"base": "Model",
"idInjection": true,
"properties": {
"hours": {"type" : "number"}
},
"validations": [{
"person" : {
"model": "Person",
"type": "belongsTo",
"foreignKey": "id"
}
}],
"relations": {},
"acls": [],
"methods": []
}

当我尝试使用 http API 插入此 Report 时:

{
"name" : "report",
"people" : [
{
"id" : "54c7926e1d621dc65495f069",
"hours" : 2
}
]
}

id 不会转换为 ObjectId 并在数据库中保留为字符串。

最佳答案

任何使用 loopback 和 mongodb 的人都会偶尔遇到这个问题。要解决环回中缺少 ObjectId 类型的问题:- 一种方法确实是使用属性作为外键来描述关系,如本文所述-换句话说,更清晰的 imo 是将属性定义为 JSON 文件中的 id

参见 model definition documentation

例如:
{
“我的身份”: {
“类型”:“字符串”,
“身份证”:真实的,
“生成”:真
}
}

现在对此属性的请求将通过传递实际 objectId 或其字符串表示来工作

关于javascript - 如何使用环回和 mongodb 将嵌套对象中的属性转换为 ObjectId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27874880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com