Easiest way to copy/clone a mongoose document instance?

前端 未结 5 1393
时光说笑
时光说笑 2020-12-09 09:31

My approach would be to get the document instance, and create a new one from the instance fields. I am sure there is a better way to do it.

5条回答
  •  鱼传尺愫
    2020-12-09 10:03

    For simply clone use this :

    Context.findOne({
        _id: context._id
    })
        .then(function(c) {
            c._id = undefined;
            c.name = context.name;
            c.address = context.address;
            c.created = Date.now();
            return Context.create(c.toObject());
        }).then(function(c) {
            return res.json({
                success: true,
                context: context
            });
        }).catch(function(err) {
            next(err, req, res);
        });
    

提交回复
热议问题