Remove property from document instance mongoose

I need to remove a property from a mongoose document instance. I found many questions that show how to remove it from the database, but that is not what I am looking for.

I need to pull out a document including a security access check box. Then I want to split that field so that it doesn't get expanded if the downstream code decides to call toObject()

and send the object back to the client.

Any thoughts?

+3


source to share


2 answers


I needed to remove the password property from the document instance, but I couldn't find anything in the API documentation. Here's what I did:

doc.set('password', null); // doc.password is null

      



Then I found that you can also do this:

delete doc._doc.password // doc.password is undefined

      

+4


source


Using a function set

with a value will null

simply assign the value, not remove it. Your best bet is to first transform the document with toObject()

(so it becomes a simple object), make your changes, and put it back in the model document:



let tempDoc = doc.toObject();
delete tempDoc.password;
doc = new this(tempDoc);

      

+1


source







All Articles