Home > OS >  How to delete property from object mongoDb mongoose nodeJs
How to delete property from object mongoDb mongoose nodeJs

Time:09-25

I am trying to delete the _id property in my function so that mongoDb create a new one for me when I try to copy a document. I have tried the following but the _id remains without being deleted

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

results still have _id property

main goal is that I am trying to copy a document that is in the templateinfo collection to the template collection.

CodePudding user response:

Use select function to exclude to _id property :

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

CodePudding user response:

You can not delete _id index from mongodb document you can only hide it using select("-id") or you can rename it while printing.

1)Hiding _id

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

2)Renaming _id Property (Add below code in mongodb model )

EmployeeSchema.set("toJSON", {
  transform: function (doc, ret, options) {
    ret.EmpRefNo = ret._id;
    delete ret._id;
  },
});
  • Related