gpt4 book ai didi

node.js - 使用 NodeJS 将附件添加到 couch db 中的文档

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:21 25 4
gpt4 key购买 nike

我想更新 couchdb 中的现有文档。我有一个图像,我想将其添加到数据库中的现有文档中,而不会丢失以前的字段。

我正在使用带有nano的nodejs。

坦克,这让我找到了正确的方向。最后我这样做:

db.get(id,{ revs_info: true }, function (error, objeto) {
if(error)
console.log('wrong id');
fs.readFile('image.jpg', function(err, data)
{
if (!err)
{
db.attachment.insert(id, 'imagen.jpg', data, 'image/jpg',{ rev: objeto._rev}, function(err, body) {
if (!err)
console.log(body);
});
}
});
});

最佳答案

你的问题不太清楚具体的问题。因此,这里只是一些有关更新文档的一般指导。

  • 设计数据库时,请确保设置 ID,而不是允许 couchdb 编辑它。这样您在更新文档时就可以直接访问该文档。
  • 更新时,您需要证明您正在更新文档的最新版本。我通常首先检索文档,并确保您要插入的文档中有最新的“_rev”。
  • 最后,如果在检索和更新文档之间有不同的进程编辑了文档,则更新可能会失败。因此,您应该捕获插入中的失败并重复该过程,直到成功。

话虽这么说,有两种方法可以存储图像:

  1. 作为附件:我相信 Nano 支持 attachment.insert()attachment.get() 函数来执行此操作。
  2. 作为引用:我通常宁愿将图像存储在其他地方,而只存储用于访问它们的 url 或文件路径。我没有太多使用 Nano,但相信您可以通过执行以下操作来做到这一点。

    doc = db.get(docname); // get the document with all existing elements 
    doc['mynewimage'] = myimageurl; // update the document with the new image
    // this assumes it's a dictionary
    db.insert(doc); // inserts the document with the correct _id (= docname)
    // and _rev

关于node.js - 使用 NodeJS 将附件添加到 couch db 中的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com