首先我要说的是,我已经做了很多研究,但我仍然很迷失。
我有一个工作版本,但我确信这是最低效的方法。我对了解规划数据库的最佳方法不是很有信心,显然我已经变得依赖 ActiveRecord。无论如何,我只是想弄清楚这些事情:
- 找出规划数据库的最佳方法(我应该如何分隔文档)
- 寻找最有效的方式来处理关系
- 找到从服务器查询的好方法
好吧,我注意到了一些事情:第一,你不能将客户端变量传递到 View 中,所以使用这样的方法是行不通的。第二,我认为可能有办法获取所有帖子,然后检查类型是否为帖子,然后返回匹配的文档,但这似乎有大量数据在移动。
一些代码:
所以我使用 Node.js、CouchDB 和 nano 作为中间件。
发布文档:
{
"_id": "post-slug",
"title": "Post Slug",
"user": "film42",
"date": 1343451412,
"type": "post"
}
用户文档:
{
"_id": "film42",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="097d6c7a7d496c71686479656c276a6664" rel="noreferrer noopener nofollow">[email protected]</a>",
"posts": [
"post-slug",
"another-post-slug"
],
"type": "user"
}
这是我目前获取所有帖子的方式(这真的很糟糕!):
function buildUserPostArray(array, user, res, i) {
db.get(user.posts[i], function(err, post_obj) {
if(i < user.posts.length) {
array.push(post_obj);
buildUserPostArray(array, user, res, i+1);
}
else {
console.log('Rendering view now.');
res.render('user.jade', {
user: user.user,
posts: array
});
}
});
}
app.get('/users/:id', function(req, res) {
db.get(req.params.id, function(err, user_obj) {
if(err) res.send('err1'); //bad id or server down
array = [];
buildUserPostArray(array, user_obj, res, 0);
});
});
我一直在使用 View ,直到我意识到我无法传递变量,然后我查看了列表,但在阅读了很多教程后我迷失了方向。
感谢您的帮助!!
最佳答案
您确实想使用 View 。只需以用户为键创建帖 subview 即可。
function(doc) {
emit(doc.user, {title: doc.title, date: doc.date, id: doc._id});
}
然后你可以简单地查询它:
GET /yourdb/_design/app/_view/by_user?key=film42
这将为您提供与该用户关联的所有 View 文档。
关于javascript - CouchDB 在 Node.js 中获取用户的所有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11706524/