使用Node.js express4.0和Node.js将多个图像附件连接到couchdb(nano)
我正在尝试使用express 4和Professional通过nano将多个图像插入couchdb。我可以使用Knowledge和nano轻松地访问和插入单个文件,但是,当我尝试一个接一个地插入文件时,会出现冲突错误。我对js和node非常陌生,我知道我对回调和异步函数的理解是有限的。这就是我现在拥有的。任何帮助都将不胜感激使用Node.js express4.0和Node.js将多个图像附件连接到couchdb(nano),express,couchdb,filestream,formidable,couchdb-nano,Express,Couchdb,Filestream,Formidable,Couchdb Nano,我正在尝试使用express 4和Professional通过nano将多个图像插入couchdb。我可以使用Knowledge和nano轻松地访问和插入单个文件,但是,当我尝试一个接一个地插入文件时,会出现冲突错误。我对js和node非常陌生,我知道我对回调和异步函数的理解是有限的。这就是我现在拥有的。任何帮助都将不胜感激 function uploadImage(req, res) { var form = new formidable.IncomingForm(), files = []
function uploadImage(req, res) {
var form = new formidable.IncomingForm(),
files = [],
fields = [];
uploadcount = 1;
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
files.push([field, file]);
var docid = fields[0][1];
getrevision();
function getRevision(){
dbn.get(docid, { revs_info: true }, function(err,body, file){
if (!err) {
exrev = body._rev;
insertImage(exrev);
}else{
console.log(err);
}
});
}
function insertImage(exrevision){
var exrev = exrevision;
fs.readFile(file.path, function (err, data) {
if (err){
console.log(err);}else{
var imagename = docid + "_" + uploadcount + ".png";
dbn.attachment.insert(docid,imagename,data,'image/png',
{ rev: exrev }, function(err,body){
if (!err) {
uploadcount++;
}else{
console.log(err);
}
});
};
});
};
});
form.on('end', function() {
console.log('done');
res.redirect('/public/customise.html');
});
form.parse(req);
}) 我找到了一个解决方案,首先将文件转储到一个临时目录中,然后在单个函数中通过nano-all将文件插入couchdb。我找不到暂停filestream以等待couchdb响应的方法,因此这种顺序方法似乎足够了。这是处理异步调用的问题。因为每个附件插入都需要文档的当前版本号,所以不能并行插入。只有在收到上一个附件的响应后,才能插入新附件 您可以使用承诺和延迟机制来执行此操作。但是,我个人使用一个名为async的包解决了一个类似的问题。在async中,您可以使用async.eachSeries串联进行这些异步调用 另一点是关于修订号,您可以只使用更轻量级的db.head函数,而不是db.get。版本号显示在etag标题下。您可以获得如下所示的转速:
// get Rev number
db.head(bookId, function(err, _, headers) {
if (!err) {
var rev = eval(headers.etag);
// do whatever you need to do with the rev number
......
}
});
{"ok":true,"id":"b2aba1ed809a4395d850e65c3ff2130c","rev":"4-59d043853f084c18530c2a94b9a2caed"}
此外,每次插入附件后,couchdb的响应如下所示:
// get Rev number
db.head(bookId, function(err, _, headers) {
if (!err) {
var rev = eval(headers.etag);
// do whatever you need to do with the rev number
......
}
});
{"ok":true,"id":"b2aba1ed809a4395d850e65c3ff2130c","rev":"4-59d043853f084c18530c2a94b9a2caed"}
rev属性将提供新的rev编号,您可以使用该编号插入下一个附件