您的代码可能会返回空结果,因为您在可能尚未从数据库中获取用户状态时调用响应。另一个问题是,如果我收到来自同一个用户的多条消息,那么调用他的状态可能是重复的。下面是一个函数,它首先从数据库中获取消息,避免用户的重复,然后获取他们的状态。
function getMessages(username, callback) {
// this would be "buffer" for senders of the messages
var users = {};
// variable for a number of total users I have - it would be used to determine
// the callback call because this function is doing async jobs
var usersCount = 0;
// helpers vars
var i = 0, user, item;
// get all the messages which recipient is "username"
db.view('privatemessages/all', {"key":username}, function (errA, resA) {
// for each of the message
resA.forEach(function (rowA) {
user = users[rowA.username];
// if user doesn't exists - add him to users list with current message
// else - add current message to existing user
if(!user) {
users[rowA.username] = {
// I guess this is the name of the sender
name: rowA.username,
// here will come his current status later
status: "",
// in this case I may only need content, so there is probably
// no need to insert whole message to array
messages: [rowA]
};
usersCount++;
} else {
user.messages.push(rowA);
}
});
// I should have all the senders with their messages
// and now I need to get their statuses
for(item in users) {
// assuming that user documents have keys based on their names
db.get(item, function(err, doc) {
i++;
// assign user status
users[item].status = doc.onlineStatus;
// when I finally fetched status of the last user, it's time to
// execute callback and rerutn my results
if(i === usersCount) {
callback(users);
}
});
}
});
}
...
getMessages(username, function(result) {
response.end(JSON.stringify(result));
});
尽管 CouchDB 是一个很棒的文档数据库,但您应该小心频繁更新现有文档,因为它在每次更新后都会创建全新的文档版本(这是因为它的MVCC模型用于实现高可用性和数据持久性)。此行为的后果是更高的磁盘空间消耗(更多数据/更新,需要更多磁盘空间 -示例),因此您应该观察它并相应地运行数据库消耗。