Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you turn a Mongoose document into a plain object?

I have a document from a mongoose find that I want to extend before JSON encoding and sending out as a response. If I try adding properties to the doc it is ignored. The properties don't appear in Object.getOwnPropertyNames(doc) making a normal extend not possible. The strange thing is that JSON.parse(JSON.encode(doc)) works and returns an object with all of the correct properties. Is there a better way to do this?

like image 794
respectTheCode Avatar asked Sep 21 '11 16:09

respectTheCode


People also ask

What does lean () do Mongoose?

The lean() function tells mongoose to not hydrate query results. In other words, the results of your queries will be the same plain JavaScript objects that you would get from using the Node. js MongoDB driver directly, with none of the mongoose magic.

What is object in Mongoose?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

What does save () do in 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 a Mongoose document?

Mongoose documents represent a one-to-one mapping to documents as stored in MongoDB. Each document is an instance of its Model. Documents vs Models. Retrieving. Updating Using save()


1 Answers

Mongoose Models inherit from Documents, which have a toObject() method. I believe what you're looking for should be the result of doc.toObject().

http://mongoosejs.com/docs/api.html#document_Document-toObject

like image 95
jmar777 Avatar answered Oct 10 '22 13:10

jmar777