【问题标题】:how to convert array to cursors in publish?如何在发布中将数组转换为游标?
【发布时间】:2013-10-29 18:03:10
【问题描述】:

以下代码:

Meteor.push("svse",function(){   
   if(UserUtils.isAdmin(this.userId)) //is Administrator?
       return Svse.find();
   var arr = ["1","1.2"]; //just a example
   var nodes = Svse.find({sid:{$in:arr}}).fetch();
   var newNodes = new Array();
   for(i in nodes){
       var newNode = nodes[i];
       newNode["son"] = ArrayUtils.intersect(arr,newNode["son"]);
       newNodes.push(newNode)
    }
    return newNodes;
});

ArrayUtils={};
Object.defineProperty(ArrayUtils,"intersect",{
value : function(a,b){
    var ai=0;
    var bi=0;
    var result = new Array();
    while( ai < a.length && bi < b.length ){
        if(a[ai] < b[bi] ) {
            ai++;
        } else if(a[ai] > b[bi] ){
            bi++; 
        } else {
            result.push(a[ai]);
            ai++;
            bi++;
        }
    }
    return result;
}
});

在流星启动时导致错误:

 sub ac338EvWTi2tpLa7H 的异常错误:
      发布函数返回一个非游标数组

如何将数组转换为游标?还是像 ArrayUtils.intersect() 一样在查找查询中处理数组操作 here

【问题讨论】:

    标签: meteor


    【解决方案1】:

    它认为 Meteor.push 是您第一行代码中的错字。

    发布函数需要返回一个集合游标或集合游标数组。来自docs

    发布函数可以返回一个 Collection.Cursor,在这种情况下,Meteor 会将该光标的文档发布到每个订阅的客户端。您还可以返回一个 Collection.Cursors 数组,在这种情况下,Meteor 将发布所有游标。

    如果您想发布 newNodes 中的内容并且不想在服务器端使用集合,请在发布中使用 this.added。例如:

    Meteor.publish("svse",function(){  
      var self = this;
      if(UserUtils.isAdmin(self.userId)) //is Administrator?
        return Svse.find();  // this would usually be done as a separate publish function
    
      var arr = ["1","1.2"]; //just a example
      Svse.find({sid:{$in:arr}}).forEach( function( newNode ){
        newNode["son"] = ArrayUtils.intersect(arr,newNode["son"]); //is this just repeating query criteria in the find?
        self.added( "Svse", newNode._id, newNode ); //Svse is the name of collection the data will be sent to on client
      });
      self.ready();
    });
    

    对于填充 newNode 的 find 和 intersect 函数,要遵循您期望发生的事情对我来说有点困难。您也许可以使用 find 并限制返回的 fields 来做同样的事情。

    【讨论】:

    • 感谢您的宝贵时间!现在我的代码也可以工作了!谢谢!!
    • 有趣的是,我尝试使用添加的方法来发布字符串数组,但我没有在客户端使用字符串“predrag”,而是得到一个字符对象:对象 {0: “p”,1:“r”,2:“e”,3:“d”,4:“r”,5:“a”,6:“g”,_​​id:0.39238154771737754}知道为什么吗?跨度>
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2015-05-10
    • 2013-07-04
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多