Reputation: 724
I am new to Loopback and working on a project where I have the following Model and Document.
{
"_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. 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)?
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.
Upvotes: 0
Views: 485
Reputation: 1073
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.
Upvotes: 1