Reputation: 1744
I'm using express 2.5.8 and mongoose 2.7.0. Here is my document schema. It's collection is where I want to store files associated with a transaction (specifically in the content String):
var documentsSchema = new Schema({
name : String,
type : String,
content : String,
uploadDate : {type: Date, default: Date.now}
});
And here is part of my transaction schema:
var transactionSchema = new Schema({
txId : ObjectId,
txStatus : {type: String, index: true, default: "started"},
documents : [{type: ObjectId, ref: 'Document'}]
});
And the express function I'm using to save a document to a transaction:
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});
});
});
});
});
}
}
The transaction gets created without any problems. And the document record gets created and everything gets set but the content.
Why is the content not getting set? fs.readFile returns the file as a buffer without any problems.
Upvotes: 0
Views: 1347
Reputation: 548
Instead of going down the path using async calls like suggested by @ebohlman, you can also use synchronous calls to get the file content.
javascript
document.content = fs.readFileSync(file.path)
Upvotes: 0
Reputation: 15003
Change:
document.content = fs.readFile(file.path, function(err, data){
To:
fs.readFile(file.path, function(err, data){
document.content = data;
Remember that readFile is asynch, so the contents aren't available until your callback gets called (the tipoff should have been that you weren't making any use of the data
parameter).
Upvotes: 1