Search code examples
node.jscouchdbcouchdb-nano

How to search by array


I have some documents with the following format:

{
 url: 'some-unique-url',
 name: 'some-name'
}

What I need to do is to select the documents which has a specific url by supplying an array which contains the url's which I need to select:

['some-unique-url', 'another-url']

Here's what my view currently looks like:

function(doc) {
  if(doc.type == 'message'){
    emit([doc.url], null);
  }
}

And here's my node.js code. I'm using nano.

db.view('message', 'by_url', {'key': urls}, function(err, body){
    res.send(body);
});

This works if I only have one item in the array but as soon as I add another item, here's what I get:

{"total_rows":18,"offset":11,"rows":[]}

I also tried startkey and endkey which also works but it acts the same way as the previous one:

db.view('message', 'by_url', {'startkey': online_users_ids, 'endkey': [online_users_ids, {}]}, function(err, body){
    res.send(body);
});

Is what I'm trying to do possible with couchdb and nano? If not, what's the closest thing I can get without losing performance? Thanks in advance!


Solution

  • You need to use keys instead of key as documented in the CouchDB API Reference.

    db.view('message', 'by_url', {'keys': urls}, function(err, body){
        res.send(body);
    });