开发者

couchdb views / reduce

开发者 https://www.devze.com 2023-03-18 21:45 出处:网络
i have 2 kind of documents, user documents where the accountdata is stored and documents where additional information about the user\'s company is stored

i have 2 kind of documents, user documents where the accountdata is stored and documents where additional information about the user's company is stored

for example:

userdocs:

{ id : ABC
, name : "user开发者_如何学C1"
, active : false
, type : "user"
}

{ id : XYZ
, name : "user2"
, active : true
, type : "user"
}

companies:

 { id : ...
  , name : "company1"
  , owner : "ABC"
  , type : "company"
  }

{ id : ...
, name : "company2"
, owner : "XYZ"
, type : "company"
}

owner links to the documents ID of the user who created the document after registration, now i would like to view only companies where the owner of the document is set to active

whats the best way to do this? can i use reduce functions? any examples would be appreciated


You can try to do this by having a denormalized database to store different type of documents (having a type attribute in each document to differenciate one document from another) and to use view collation.


As you can see I have a type attribute in each doc. Anyway, I solved this by using a lists function. Perhaps its not the best way to do this but so far its working just fine for my usecase. I will sure have a look into view collation but its a little bit confusing.


i use this http://wiki.apache.org/couchdb/Formatting_with_Show_and_List to transform my result of the view and build a json which looks like the standard output of a view, code looks something like this:

in my view i only emit users which are active

 while(row = getRow()) {
    if(row.value.type=="user") 
      active.push(row.value.id)
    if(row.value.type=="companies")
      companies.push(row)
 }
 for(var i = 0; i < companies.length; i++){
   if(active.indexOf(companies[i].value.owner) != -1)
     res.push(companies[i])
 }
 send('{\"total_rows\":'+companies.length+',\"rows\":[')
 for(var i = 0; i < res.length;i++) {
  send(toJSON(res[i]))
  if(i+1 < res.length)
    send(',')
  }
 send(']}')

as i said thats perhaps not how it should be done :) but perhaps someone can give me an example how that would work with view collation

0

精彩评论

暂无评论...
验证码 换一张
取 消