Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

485
Vistas
how to copy or clone a document in MongoDB Collection using mongoose and nodeJS

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
  }

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda