                 err.status = 500
                 next err
             else
-                log.info "Data sent to #{replicate.target.recipientUrl}"
+                log.info "Data sent to #{target.recipientUrl}"
 
                 # Update the target with the repID if the sharing is continuous
                 if replicate.continuous
-                    db.get replicate.id, (err, doc) ->
+
+                    i = doc.targets.indexOf target
+                    doc.targets[i].repID = repID
+
+                    db.merge doc._id, doc, (err, result) ->
                         return next err if err?
 
-                        # Find the target in the db and update it
-                        targetUrl = replicate.target.recipientUrl
-                        for target, i in doc.targets
-                            if target.recipientUrl is targetUrl
-                                target.repID = repID
-
-                        db.merge replicate.id, doc, (err, result) ->
-                            return next err if err?
-
-                            res.status(200).send success: true
+                        res.status(200).send success: true
                 else
                     res.status(200).send success: true
 

        return next err if err?

        # Get the answering target
        for t in doc.targets
            if t.recipientUrl is answer.recipientUrl
                target = t

        unless target?
            err = new Error "#{answer.recipientUrl} not found for this sharing"

        db.merge doc._id, doc, (err, result) ->
            return next err if err?

            # Params structure for the replication
            share =
                target : target
                doc    : doc

            req.share = share
            next()


# Replicate documents to the target url

# Params must contain:
#   doc        -> the Sharing document
#   target     -> contains the url and the token of the target
module.exports.replicate = (req, res, next) ->
    share = req.share

    # Replicate only if the target has accepted, i.e. gave a token
    if share.target.token?
        doc = share.doc
        target = share.target

        # Retrieve all the docIDs
        docIDs = (rule.id for rule in doc.rules)
        replicate =
            id          : doc._id
            target      : target
            docIDs      : docIDs
            continuous  : doc.continuous

        Sharing.replicateDocs replicate, (err, repID) ->
            if err?
                next err
