简体   繁体   中英

How to emit two separate documents concurrently in CouchDB?

In CouchDB I would like to concurrently emit an object of type country and of type city . Is this possible in just one function?

Via Linked Documents I can emit an object value which is {_id:doc.xxx} like so:

function(doc) {
    if (doc.cities) {
        for (var i in doc.cities) {
            emit(doc.name, {_id: doc.cities[i]});
        }          
    }               
}

The function down below is my suggestions but it's not working because the second if-part will be never reached.

function(doc) {
    if (doc.type == 'country') {
      emit(doc.name, null);
    } else if (doc.cities) {    
    for (var i in doc.cities) {
          emit(doc.name, {_id: doc.cities[i]});
      } 
  }
}

Documents:

// Country
{
  "_id": "country.123",
  "name": "France",
  "type": "country",
  "cities": [
    "city.123"
    ]
}

// City
{
  "_id": "city.123",
  "name": "Paris",
  "type": "city",
}

Update 1

I tried removing the else if as Dominic suggested. Now nothing gets emitted unfortunately.

function(doc) {
    if (doc.type == 'country') {
      emit(doc.name, null);
          for (var i in doc.cities) {
            emit(doc.name, {_id: doc.cities[i]});
          } 
    }
}

I assume you want to emit the country document plus the linked city document?

function(doc) {
  if (doc.type == 'country') {
    emit(doc._id, doc)
    if (doc.cities) {    
      for (var i in doc.cities) {
        emit(doc.name, {_id: doc.cities[i]});
      } 
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM