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
}