2012-07-09 42 views
0

我正在使用express 2.5.8和mongoose 2.7.0。這是我的文檔架構。它的收藏是我想要的存儲與交易(特別是在內容字符串)相關文件:爲什麼不能保存mongodb中的文件內容

var documentsSchema = new Schema({ 
    name   : String, 
    type   : String, 
    content   : String,  
    uploadDate  : {type: Date, default: Date.now} 
}); 

這裏是我的交易模式的一部分:

var transactionSchema = new Schema({ 
    txId   : ObjectId, 
    txStatus  : {type: String, index: true, default: "started"}, 
    documents  : [{type: ObjectId, ref: 'Document'}] 
}); 

而且明確功能我m用於將文檔保存到交易中:

function uploadFile(req, res){ 
    var file = req.files.file; 
    console.log(file.path); 
    if(file.type != 'application/pdf'){ 
     res.render('./tx/application/uploadResult', {result: 'File must be pdf'}); 
    } else if(file.size > 1024 * 1024) { 
     res.render('./tx/application/uploadResult', {result: 'File is too big'}); 
    } else{ 
     var document = new Document(); 
     document.name = file.name; 
     document.type = file.type; 
     document.content = fs.readFile(file.path, function(err, data){ 
      document.save(function(err, document){ 
       if(err) throw err; 
       Transaction.findById(req.body.ltxId, function(err, tx){ 
        tx.documents.push(document._id); 
        tx.save(function(err, tx){ 
         res.render('./tx/application/uploadResult', {result: 'ok', fileId: document._id}); 
        }); 
       }); 
      }); 
     }); 
    } 
} 

創建交易時沒有任何問題。文檔記錄被創建,所有內容都被設置。

爲什麼沒有設置內容? fs.readFile將文件作爲緩衝區返回而不會出現任何問題。

回答

1

變化:

document.content = fs.readFile(file.path, function(err, data){ 

要:

fs.readFile(file.path, function(err, data){ 
     document.content = data; 

記住READFILE就是非同步,所以直到你的回調函數被調用的內容是不可用(在跳球應該是你間沒有」不要使用data參數)。

+0

arg,我知道。謝謝! – 2012-07-10 06:12:04

0

您可以使用同步調用來獲取文件內容,而不是像@ebohlman, 建議的那樣使用異步調用的路徑。

javascript document.content = fs.readFileSync(file.path)

相關問題