node.js - Why won't this save file content in mongodb -


I am using Express 2.5.8 and Mongoose 2.7.0 Here is my document schema. This is the archive where I want to store files related to a transaction (especially in the content string):

  var documentsSchema = new schema ({name: string , Type: string, content: string, uploaddate: {type: date, default: date.So}});   

And here is part of my transaction schema:

  var transactionSchema = new schema ({txId: ObjectId, txStatus: {type: String, index: True, default: "start"}, document: [{type: object id, ref: 'document'}]});   

and the Express Function that I am using to save a document in a transaction:

  function upload file (request, res) {var file = Req Files.file; Console.log (file.path); If (file.type! = 'Application / pdf') {res.render ('./tx / application / uploadResult', {Result: 'File should be PDF'}); } And if (file.size> 1024 * 1024) {res.render ('./tx / application / uploadResult', {Result: 'File is too large'}); } Else {var document = new document (); Document.name = file.name; Document.type = file.type; Document.content = fs.readFile (file.path, function (error, data) {document.save (function (mistake, document) {If (mistake) becomes a mistake; Transaction.findById (req.body.ltxId, function , Tx) {tx.documents.push (document._id); tx.save (function (err, tx) {res.render ('./tx / application / uploadResult', {Result: 'OK', file ID : Document ._id});})}});});}); }}   

The transaction happens without any problem and document record is created and everything is set up, but the content.

Why is not the content being set? Fs.readFile file returns as a buffer without any problem.

Replace:

  document.content = fs.readFile (file ) (File), function (fault, data) {document}.  
 

For:

  fs.readFile content = data; Remember   

Remember that readFile is asynch, so the content is not available unless your callback is called (you should have tipoff that you have the data parameter) .

Comments