如何使用loopback和mongodb将嵌套对象中的属性转换为ObjectId?
假设我有以下模型定义:
{ "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": [] }
现在我想在人物数组中的每个对象(要像report.people [0] .id)访问id属性,它应该被插入到ObjectId插入和更新。 但是,loopback没有ObjectId
types,唯一的方法似乎是使用关系,但外键应该如何?
有没有什么办法可以在插入和更新时将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并保持为数据库上的string。
任何玩loopback和mongodb的人都会偶尔碰到这个。 为了解决在loopback中缺lessObjectIdtypes的问题:一种方法是确实描述一个使用属性作为外键的关系,正如本文所讨论的 – 另一种方式是,更简洁的方法是将属性定义为一个id JSON文件
请参阅模型定义文档
例如: { "myId": { "type": "string", "id": true, "generated": true } }
现在对这个属性的请求将会通过调用objectId或者它的string表示