                 binary =
                     docType: "Binary"
                 db.save binary, (err, binDoc) ->
-                    attachBinary binDoc
+                    binary = binDoc
+                    log.info "binary #{name} ready for storage"
+                    stream = db.saveAttachment binary, fileData, (err, binDoc) ->
+                        if err
+                            log.error "#{JSON.stringify err}"
+                            form.emit 'error', new Error err.error
+                        else
+                            log.info "Binary #{name} stored in Couchdb"
+
+                            # Once binary is stored, it updates doc link to the
+                            # binary.
+                            bin =
+                                id: binDoc.id
+                                rev: binDoc.rev
+
+                            if req.doc.binary
+                                binList = req.doc.binary
+                            else
+                                binList = {}
+                            binList[name] = bin
+                            db.merge req.doc._id, binary: binList, (err) ->
+                                res.send 201, success: true
+                    part.pipe stream
 
     form.on 'progress', (bytesReceived, bytesExpected) ->
 

    name = req.params.name
    if req.doc.binary and req.doc.binary[name]

        # Build stream for
        stream = db.getAttachment req.doc.binary[name].id, 'file', (err) ->
            if err and err.error = "not_found"
                err = new Error "not found"

                next err
            else if err
                next new Error err.error

        # Use streaming to avoid high memory consumption.
        stream.pipe res
