环回推送阵列 [英] Loopback push array
问题描述
如何制作更新/推送的自定义 remoteMethod
,不覆盖,属性阵列
。
所以基本上将
数据推送到模型的数组属性。
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.
我在文档中找不到任何明确的例子,除了 .add()
帮助器方法,但需要 embedsOne
或其他一些关系。
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.
但如果我有单 模型
在我的整个应用程序中,只想将
一些数据推送到 ID
。
所以最后得到一个端点,如:
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
而 POST
的正文将是:
{
id: "foo",
data: "bar"
}
(或者最好没有 id
,并且 id
autoInserted
,因为它是一个数组,并且我不需要每个项目的id, data
部分应该是可搜索的with filters / where)
(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)
到目前为止,我有:
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.
推荐答案
你已经使你的方法非静态,这很好。
You have made your method non-static, which is good.
现在,如果您的数组属性被称为 MyArray
,我会尝试以下方式:
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)
};
由于您的远程方法是非静态的,您应该能够使用<$ c $访问该实例C>此。我怀疑你是否可以通过编写 this.someProperty
直接访问属性,请尝试一下,如果这不起作用,请告诉我。
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.
然后批量创建只需向远程发出标准POST请求
Then to create in bulk just make a standard POST request to your remote
POST /Thing/{id}/pushData
只需像这样写你的JSON
just write your JSON like this
{
{
data: "bar"
},
{
data: "foo"
},
//etc
}
这应该在数组属性中添加两个元素。
This should add two elements to the array property.
让我知道这是否有用
这篇关于环回推送阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!