[英]Push Data into Array in Loopback Model
I am new to Loopback and working on a project where I have the following Model and Document. 我是Loopback的新手,正在从事具有以下模型和文档的项目。
{
"_id" : ObjectId("5c9b44cc618c1bbe8780e38b"),
"userId" : ObjectId("5bae3ea215e11e0018b914c1"),
"providers" : [
"1629132790",
"1467401216",
"1356405641",
"1952465288",
"1447314513",
"1003803495"
],
"countByType" : {
"doctors" : 2,
"laboratories" : 3,
"hospitals" : 1,
"imagingCenters" : 0
}
}
I am basically trying to add a new item to an array in base class Model. 我基本上是在尝试向基类Model中的数组添加新项。 When a new user is created, an empty array is added for 'providers'.
创建新用户时,将为“提供者”添加一个空数组。 There is no model for providers.
没有提供者的模型。 It is just an array which can hold a list of providers.
它只是一个可以容纳提供者列表的数组。
How do I add a new providerId to the list of providers if providerId is not there(Add a string to the list)? 如果providerId不存在,如何将新的providerId添加到提供商列表中(将字符串添加到列表中)?
This is my Provider Model 这是我的提供者模型
{
"name": "UserProviders",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"userId": {
"type": "objectId",
"required": true,
"index": {
"unique": true
}
},
"providers": {
"type": [
"any"
],
"default": []
},
"countByType": {
"type": "object",
"default": {
"doctors": 0,
"labs": 0,
"hospitals": 0,
"imagingCenters": 0
}
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Any help would be really appreciated. 任何帮助将非常感激。
I would do two things: first, I would add a custom model method for adding a new provider (that accepts both one string or array of strings), for example: 我将做两件事:首先,我将添加一个自定义模型方法来添加新的提供程序(接受一个字符串或字符串数组),例如:
const provider = async Provider.findOne({id: someId});
provider.addProviders([value1, value2]);
await provider.save();
Then, to make sure that it won't save rubbish values, I would add a custom validator that checks for duplicates in the array before you save the instance and throws an error or removes duplicates. 然后,为确保它不会保存垃圾值,我将添加一个自定义验证程序,该验证程序在保存实例并引发错误或删除重复项之前检查数组中是否存在重复项。 You can read here how to add a custom validation function to your model.
您可以在此处阅读如何向模型添加自定义验证功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.