couchbase reduce by date in node.js

2019-07-13 15:38发布

I have to make some code which filter active user with couchbase, node.js

I have some users documents, and I made a view with the following coded :

I made a view called "bydate" with the following code :

function (doc, meta) {  
    if(meta.type == 'json') { 
        if(doc.type == 'user') { 
           if (doc.lastUpdate){ 
                emit(dateToArray(doc.lastUpdate),doc.name); }
        }
    }
} 

I have to filter by day, month or year using the "group_level" setting in couchbase console , however I have unable to filter it properly on node.js side

here is my node.js code

router.get("/activetodaycount",
    function(request,response,next)
    {

            var couchbase = require('couchbase');
            var ViewQuery = couchbase.ViewQuery;

            var params =
            { 
               'reduce'         : true
              , 'group_level'   : 3
              , 'connection_timeout' : 600000
              , 'limit' : 10
              , 'skip' : 0
              , 'stale' : false
              , 'inclusive_end' : false
            };

            var query = ViewQuery.from('users', 'bydate')

            couch.query(query, params, function(error, data) 
            {

                if (error)
                {
                    return next(error);
                }

                console.log(data)

                var out = [];

                for( var i = 0;i<data.length; i++ ) 
                {
                    console.log(data[i])
                    var user = data[i].id;
                    out.push(user)
                }

                response.json({'cnt':out.length});
             });  

    }

the console output is :

{ key : null, value : XX}

I don't understand why I don't get the dateToArray result as key. any ideas ?

Edit :

here is the output from filter result in the couchbase console:

Key     Value
[2015,1,2,13,56,0]
user:0af1144d-a23b-4098-9079-13dea8eb24b1   null
[2015,1,2,13,56,0]
user:58bc2ca5-9c50-4a5f-a056-e2a7b32450fd   null
[2015,1,2,16,43,57]
user:6b5f1c46-bf1d-43d6-bf25-b3f1a2495cdf   null

1条回答
老娘就宠你
2楼-- · 2019-07-13 15:56

I suspect you're using the 2.0.3 (latest) version of the node SDK, which ignores theparamsobject you're passing to thequeryfunction, because it expects theViewQueryobject itself to specify the options.

Try this:

var couchbase = require('couchbase');
var ViewQuery = couchbase.ViewQuery;
var cluster = new couchbase.Cluster('localhost');
var bucket = cluster.openBucket('default', console.log);

var query = ViewQuery.from('users', 'bydate')
                     .group_level(6)
                     .stale(ViewQuery.Update.BEFORE)
                     .limit(10)
                     .range([2015,1,2,13,56,0], [2015,1,2,16,43,57], true);

bucket.query(query, console.log);  

Note that therangemethod takes the start key, end key, and inclusive end boolean flag.

查看更多
登录 后发表回答