【问题标题】:Meteor Aldeed - Collection2 - get length of an array field to use in autoValueMeteor Aldeed - Collection2 - 获取要在 autoValue 中使用的数组字段的长度
【发布时间】:2016-10-08 23:20:53
【问题描述】:

大家好,我在我的项目中使用Collection2,我想获取一个字段的长度,该字段的类型为:来自另一个字段的数组

这是我的代码示例

        yes: {
            type: Array,
            optional: true
        },
        "yes.$": {
            type: Object
        },
        yesLength: {
            type: Number,
            autoValue: function(){
                var lenYes = this.field("yes").length;
                console.log(this.field("yes"));
                console.log(lenYes)
                return lenYes;
            },
            optional: false
        },

当我将 this.field("yes") 记录到控制台时,它看起来很好,但是当我记录 lenYes 即 this.field("yes").length 时,我得到了未定义。我在这里做错了吗?谢谢

【问题讨论】:

    标签: mongodb meteor collections meteor-collection2


    【解决方案1】:

    在 Collection2 中,您只能获取其他字段的值如果它们在修饰符中是$set。通常情况并非如此,在这种情况下,您实际上需要 .findOne() 来获取文档,然后从中获取当前值。

    您可以将 Collection2 视为更改的验证器,但它不是当前值的验证器。

    由于您的yesLength 应该表示数组的长度,并且数组的长度可以通过修饰符以许多不可预知的方式更改,因此使用collection hook 来计算yesLength 可能更有意义更新后

    MyCollection.after.insert(function(userId,doc){
      if ( doc.yes ){ // the yes array exists
        MyCollection.direct.update(doc._id,{ $set: { yesLength: doc.yes.length }});
      }
    });
    
    MyCollection.after.update(function(userId,doc,fieldNames){
      if ( fieldNames.indexOf('yes') > -1 ) { // yes array was modified
        MyCollection.direct.update(doc._id,{ $set: { yesLength: doc.yes.length }});
      }
    });
    

    您需要使用.direct 来避免在更新计数器时重新进入您的钩子。

    【讨论】:

    • 谢谢@michelFloyd。我有办法解决我想要实现的目标。我希望 yesLength 字段的值设置为数组的“yes”字段的长度
    • 嗨,谢谢,但我在控制台中收到此错误调用方法'/questions/update'时出现异常错误:过滤掉不在架构中的键后,您的修饰符现在为空 i> 每当我尝试更新或插入我的收藏时
    • 这意味着您正在使用架构中不存在的字段进行更新。您可能完全从架构中删除了yesLength。将其保留为Number
    • 非常感谢米歇尔·弗洛伊德。我工作得很好
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多