我使用的是express 2.5.8和mongoose 2.7.0。这是我的文档架构。它的集合是我想要存储与事务相关联的文件的地方(特别是在内容字符串中):
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'}]
});
还有我用来将文档保存到事务的快捷功能:
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将文件作为缓冲区返回,不会出现任何问题。
更改:
document.content = fs.readFile(file.path, function(err, data){
收件人:
fs.readFile(file.path, function(err, data){
document.content = data;
请记住,readFile是异步的,因此在调用回调之前,内容不可用(提示应该是您没有使用data
参数)。
不像@ebolman建议的那样使用异步调用,您还可以使用同步调用来获取文件内容。
javascript
document.content = fs.readFileSync(file.path)