问题
How would I go about making a custom remoteMethod that updates/pushes, not overrides, a property that is an array.
So basically push data to an array property of a model.
I can't find any clear examples of this in the documentation, except for an .add() helper method, but that requires an embedsOne or some other relation.
But what if I have a single Model in my whole app and would just want to push some data to an id.
So ending up with an endpoint like:
POST /Thing/{id}/pushData
And the body to POST would be:
{
id: "foo",
data: "bar"
}
(Or preferably without id, and have the id autoInserted, since it's an array, and I don't need an id for each item, the data part should be searchable with filters/where)
So far I have:
Thing.remoteMethod (
'pushData',
{
isStatic: false,
http: {path: '/pushData', verb: 'post'},
accepts: [
{ arg: 'data', type: 'array', http: { source: 'body' } }
],
returns: {arg: 'put', type: 'string'},
description: 'push some Data'
}
);
Thing.prototype.pushData = function(data, cb) {
data.forEach(function (result) {
// ??
});
cb(null, data)
};
And as far as I can see, the default endpoints only allow single instances to be added, but I want to update in bulk.
回答1:
You have made your method non-static, which is good.
Now, if your array property is called MyArray, I would try something along the lines of :
Thing.remoteMethod (
'pushData',
{
isStatic: false,
http: {path: '/pushData', verb: 'post'},
accepts: [
{ arg: 'data', type: 'array', http: { source: 'body' } }
],
returns: {arg: 'put', type: 'string'},
description: 'push some Data'
}
);
Thing.prototype.pushData = function(data, cb) {
thingInstance = this;
data.forEach(function (result) {
thingInstance.MyArray.push(result.data);
});
cb(null, data)
};
Since your remote method is non-static, you should able to access the instance using this. I have a doubt whether or not you can directly access properties that way by writing this.someProperty, please try it and let me know if that doesn't work.
Then to create in bulk just make a standard POST request to your remote
POST /Thing/{id}/pushData
just write your JSON like this
{
{
data: "bar"
},
{
data: "foo"
},
//etc
}
This should add two elements to the array property.
Let me know if this is helpful
来源:https://stackoverflow.com/questions/35223393/loopback-push-array