简体   繁体   中英

How to create a copy of a document before saving with Mongoose?

I have a document which user updates via web UI. I want to create a copy of the document and save it to the same collection before new changes are saved.

Here is the hook I am trying to consume:

PrototypeSchema.pre('save', function(next) {
  const protoCopy = new Prototype(proto.toObject())
  protoCopy.save()

  this.lastUpdateDate = new Date()
  next()
})

This causes infinite pre-save hook to be executed. How do I make a copy of the document and save both new version (as the same document) and previous one (as a new document)?

According to the pre-save middleware documentation , it does not run when updating a document but when inserting. For this you should use the pre-update. However, I am pretty sure that when the middleware runs the document already contains the changes so saving a copy of that document would be duplicating the updated document, and not saving a copy of the original document. I think the easier way may be to save the new document (with the old data) at the same place (controller or whatever) where you are updating the original document:

var originalId = "foo";
var changes = {foo: "bar"};

Prototype.findById(originalId, function(err, original){
    if (err) return { err };
    Prototype.insert(original, function(err){
        if (err) return { err };
        Prototype.findAndUpdate({_id: originalId}, changes, { new: true }, function(err, updated){
            return { err, updated };
        });
    });
});

EDIT:

About what I said (and the documentation says) about pre-save middleware not running when updating a document, I just thought I'm not sure if this depends on the version of Mongoose you're using. In any case, my code would work with any version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM