【问题标题】:Meteor, SimpleSchema, meteor-collection2 - Adding to arrayMeteor、SimpleSchema、meteor-collection2 - 添加到数组
【发布时间】:2018-07-03 04:53:10
【问题描述】:

我已将我的归档和 shema 定义为:

storageArticles:
{
  type: Array,
  autoValue: function() {
    return [];
  },
  label: 'Articless added to storage.',
},
'storageArticles.$': {
  type: String
}

当我尝试使用(在我的服务器端方法中)更新此字段时:

Storages.update(storageId , {$set: { "storageArticles" : articleId }});

一切正常,但数据没有添加到数组中。

你能给我一些指导来解决这个问题吗?

编辑

编辑添加了有关此问题的更多详细信息,也许这是我的错误。

'articles.articleAddToStorage': function articleAddToStorage(storageId,articleId) {
    check(storageId, String);
    check(articleId, String);

    try {

      Articles.update(articleId, {  $set: {articleAssignedToStorage:true}});
      Storages.update(storageId , {$addToSet: { "storageArticles" : articleId }});

    } catch (exception) {
      handleMethodException(exception);
    }
  }

handleAddToStorage()
  {

    const articleId = this.props.articleId;
    const storageId = this.state.storageId;
    const history = this.props.history;

    if(storageId!="")
    {

      Meteor.call('articles.articleAddToStorage', storageId,articleId, (error) => {

        if (error) {
          Bert.alert(error.reason, 'danger');
        } else {

          Bert.alert("Article assigned to storage", 'success');

        }
      });
    }
    else {
    Bert.alert("Plese select storage", 'warning');

    }
  }

【问题讨论】:

    标签: meteor simple-schema meteor-collection2


    【解决方案1】:

    使用字段集运算符

    随行

    Storages.update(storageId , {$set: { "storageArticles" : articleId }});
    

    您基本上尝试将字符串值 (articleId) set 传递给定义为字符串数组的字段。

    这只有在将值数组设置为 storageArticles(从而覆盖整个字段)时才有意义:

    Storages.update(storageId , {$set: { "storageArticles" : [articleId] }});
    

    使用数组更新操作符

    如果您想推送或拉取值,您可以查找mongo array update operators(在此处列出一些示例):

    $addToSet 仅在元素不存在时将元素添加到数组中 在集合中。

    Storages.update(storageId , {$addToSet: { "storageArticles" : articleId }});
    

    $pop 删除数组的第一项或最后一项。

    Storages.update(storageId , { $pop : 1 });
    

    $pull 移除所有匹配指定查询的数组元素。

    Storages.update(storageId , {$pull: { "storageArticles" : articleId }});
    

    $push 将一个项目添加到数组中。

    Storages.update(storageId , {$push: { "storageArticles" : articleId }});
    

    $pullAll 从数组中删除所有匹配的值。

    Storages.update(storageId , {$pullAll: { "storageArticles" : [articleId1, articleId2] }});
    

    【讨论】:

    • 通过使用 Storages.update(storageId , {$addToSet: { "storageArticles" : articleId }});我收到此错误:更新失败:错误:存储文章必须是字符串类型
    • 在新文档还是现有文档上?我问是因为当您在之前将字段设置为 articleId(一个字符串)的文档上尝试它时,该字段不再是一个数组。在其上使用数组更新方法可能会导致该错误。
    • 我打开了 Robo 3T,我看到 storageArticles 的类型是数组,但是当我尝试更新它时它不起作用,我已经用更多细节编辑了我的问题。
    • 尝试删除autoValue - 你不需要初始化一个空数组。
    • 谢谢@MichelFloyd,这与 Jankapunkt 先生的建议一起解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2014-01-27
    相关资源
    最近更新 更多