wilsonpage
wilsonpage

Reputation: 17610

MongooseJS: How can I turn a Mongoose Collection into a standard Javascript array

I am attempting to send a database collection directly to the client. When inspecting the collection on the client it appears to be a Mongoose object with various mongoose methods attached to it. How can I get to the raw collection data and ditch the mongoose object?

I have managed to get the following to do what I want, but seems a little hacky:

var normalJavascriptArray = JSON.parse(JSON.stringify(myMongooseCollection));

Upvotes: 3

Views: 1976

Answers (1)

Zeke Nierenberg
Zeke Nierenberg

Reputation: 2206

You can call the toObject() function. I know it says toObject, but in this case it returns an array.

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

What I actually had to do when trying it was map through the resulting array and call toObject on each of its children. The mongoose docs were talking about a subdocument array I think.

MyMongooseCollection.map(function(item){
    return item.toObject();
}

Tested. It works.

Upvotes: 3

Related Questions