假设在 node.js 上通过 nano 打开了一个 couchdb 会话
var dbserv = require('nano')('http://localhost:5984');
在 couchdb 服务器dbserv
可以访问的地方,有一个用户数据库users
,其中用户的字段groups
是一个数组。
如果我想更新groups
中的用户jim
,users
我将如何在不替换整个文档的情况下这样做?
假设在 node.js 上通过 nano 打开了一个 couchdb 会话
var dbserv = require('nano')('http://localhost:5984');
在 couchdb 服务器dbserv
可以访问的地方,有一个用户数据库users
,其中用户的字段groups
是一个数组。
如果我想更新groups
中的用户jim
,users
我将如何在不替换整个文档的情况下这样做?
要创建更新处理程序,请编写设计文档:
{
"_id": "_design/yourapp",
"updates": {
"foo": "function(doc, req) {
doc.groups.push(req.query.bar); // or do whatever you like with it
return [doc, 'done'];
}"
}
}
并使用 id 将其放入您的数据库中_design/yourapp
,然后像这样获取它:
http://localhost:5984/users/_design/yourapp/_update/foo/jim?bar=baz
var dbserv = require('nano')('http://localhost:5984');
var db = dbserv.use('users');
var designdoc = {/* The above design document */};
db.insert(designdoc);
db.get('_design/yourapp/_update/foo/jim', {bar: 'baz'});
请注意,您只需要插入一次设计文档,您甚至可以手动使用curl
,然后更新您的文档只需按照上述说明发出 GET 请求。
Disclaimer: untested and I never used nano before, but it should be on the lines of what you have to do.
Found a way to make updates, without all _design needs and such. The issue with Nano CouchDB is that the insert doesn't really provide a place to send the correct _rev that is needed for an update. Anyhow, there is a work around. What one needs to do, is to get the _rev value from the _id you want to update. So you use Nano db.get as the big function, get the _rev value and update your document. Here is a code sample:
users.get('document_name', function(err, doc) {
updaterev = doc._rev;
users.insert({title:'here_ya_go',_rev:updaterev},'document_name', function(err, body , header) {
if (!err)
{
console.log(body);
res.send('update website succeed');
}
else
{
console.log(err.error);
}
});
});
When the db.insert functions are inside db.get function, it gives us a chance to grab hold of the _rev and update out document.
I know, I probably didn't invent this, but it's important to have this piece of code to grab and go. Good luck.