Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove property from mongoose document instance

I need to remove a property from a mongoose document instance. I've found a lot of questions that show how to remove it from the database, but that's not what I'm looking for.

I need to pull the document down including a field to check security access, I then want to strip that field so that it doesn't get disclosed if downstream code decides to call toObject() and send the object back to the client.

Any thoughts?

like image 872
joshperry Avatar asked Aug 05 '15 23:08

joshperry


People also ask

How do you delete an item from MongoDB using Mongoose?

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.

What is the Mongoose command used to delete an item?

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.

What does .save do Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

What is an instance of a model in Mongoose?

An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.


1 Answers

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

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

Then I found you can also do this:

delete doc._doc.password // doc.password is undefined
like image 130
sergeyz Avatar answered Nov 10 '22 21:11

sergeyz