I'm trying to delete a key before sending data back to the browser. For some reason, maybe because it is a mongoose object, this isn't working:
delete myObject.property
If I do console.log(delete myObject.property)
I get true
which I understand means the property was not deleted. How can I get rid of this key?
(More background: I know I could leave it off by using a mongoose select query, but I do need to select the key initially. I can also set it to null, which works fine, but I'd much rather get rid of the key completely)
There is currently no method called deleteById() in mongoose. However, there is the deleteOne() method with takes a parameter, filter , which indicates which document to delete. Simply pass the _id as the filter and the document will be deleted.
Mongoose | deleteOne() Function The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option.
The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.
You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.
As MikaS states, you need to convert to convert the Mongoose document object into an ordinary object first:
const newObj = myObject.toObject();
delete newObj.property;
This should be fine if you're doing this once. However, if you have to repeat this logic everywhere you return this this type of document with certain keys omitted or other transformations, you should define transformations on your schema:
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// any kind of simple/complicated transformation logic here
// remove the _id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
doc.toObject(); // { name: 'Wreck-it Ralph' }
Read about Document#toObject and transformations in the docs
Convert the Mongoose document object to an ordinary Javascript object first:
const newObj = myObject.toObject();
delete newObj.property;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With