简体   繁体   English

如何在使用Mongoose保存之前创建文档的副本?

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

I have a document which user updates via web UI. 我有一个用户通过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. 关于我所说的(以及文档中说的)关于在更新文档时未运行的预保存中间件,我只是想我不确定这是否取决于您正在使用的Mongoose版本。 In any case, my code would work with any version. 无论如何,我的代码适用于任何版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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