Home > OS >  how to copy or clone a document in MongoDB Collection using mongoose and nodeJS
how to copy or clone a document in MongoDB Collection using mongoose and nodeJS

Time:09-25

how can we clone a document to the same or new collection with a new _id

here is the found data from the query coming from "doc" (res.query)

[
  {
    _id: new ObjectId("614d4766fb2600340fdb2904"),
    templateName: 'first template',
    _ref: '1632454502ref',
    owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
    __v: 0
  }
]

not working:

TemplateInfo.find(req.query).exec(function (err, doc) {
      console.log("document", doc);
      var newdoc = new TemplateInfo(doc[0]);
      delete newdoc._id; //= mongoose.Types.ObjectId();
      newdoc.save();
    });

This works but the data is now a object which is not inserted correctly

TemplateInfo.find(req.query).exec(function (err, doc) {
      console.log("document", doc);
      var newdoc = new TemplateInfo(doc);
      newdoc._id = mongoose.Types.ObjectId();
      newdoc.save();
    });

results but wrong:

{
    "0": {
        "_id": {
            "$oid": "614d4766fb2600340fdb2904"
        },
        "templateName": "first template",
        "_ref": "1632454502ref",
        "owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
        "__v": 0
    },
    "_id": {
        "$oid": "614e34dbf288909e4713282b"
    },
    "__v": 0
}

Works correctly however I need to get my data from the query not manually entered

const docData = {
      //_id: new ObjectId("614d4766fb2600340fdb2904"),
      templateName: "first template",
      _ref: "1632454502ref",
      owner: "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
      __v: 0,
    };

    TemplateInfo.find(req.query).exec(function (err, doc) {
      console.log("document", doc);
      var newdoc = new TemplateInfo(docData);
      newdoc._id = mongoose.Types.ObjectId();
      newdoc.save();
    });

results correct but I manually entered them as a variable:

{
    "_id": {
        "$oid": "614e378700b5bd9c7ba5ef37"
    },
    "templateName": "first template",
    "_ref": "1632454502ref",
    "owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
    "__v": 0
}

I am hoping to have a copy of a document with different _id in the mongoDB collection


  {
    _id: new ObjectId("614d4766fb2600340fdb2904"),
    templateName: 'first template',
    _ref: '1632454502ref',
    owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
    __v: 0
  }

CodePudding user response:

Following is the example for copy/clone document in mongoose.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/test');

const Cat = mongoose.model('Cat', { name: String });

Cat.find({_id:'614e440b771169c71a34dae9'}).exec(function (err, doc) {
    console.log("document", doc);
    
    doc.forEach(node => insertBatch(node));
  });

  function insertBatch( doc) {
    var id;
    
    id = mongoose.Types.ObjectId();
    doc._id =  id;
    console.log("doc", doc);

    const kitty = mongoose.model('Cat');

    kitty.findOneAndUpdate({_id: id}, doc, {upsert: true}, function(err, doc1) {
        if (err) return res.send(500, {error: err});
        console.log('Succesfully saved.');
    });
  }
  

"614e440b771169c71a34dae9" can be any id in collection

  • Related