我使用的是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'}]
});以及我用来将文档保存到事务中的express函数:
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将文件作为缓冲区返回,没有任何问题。
发布于 2012-07-10 08:50:52
更改:
document.content = fs.readFile(file.path, function(err, data){至:
fs.readFile(file.path, function(err, data){
document.content = data;请记住,readFile是异步的,因此在调用回调之前,内容是不可用的(提示应该是您没有使用data参数)。
发布于 2015-02-13 01:55:42
您也可以使用同步调用来获取文件内容,而不是像@ebohlman建议的那样使用异步调用。
javascript document.content = fs.readFileSync(file.path)
https://stackoverflow.com/questions/11404803
复制相似问题