MongooseJS: How can I turn Mongoose collection into standard Javascript array
I am trying to send a collection of a database directly to a client. When validating the collection on the client, it looks like a Mongoose object with various mongoose methods attached. How can I get the raw collection data and discard the mongoose object?
I was able to do the following to do what I want, but it seems a little hacky:
var normalJavascriptArray = JSON.parse(JSON.stringify(myMongooseCollection));
+3
source to share
1 answer
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 really needed to do when I tried to do this was map through the resulting array and call toObject on each of its children. The mongoose talks talked about an array of subdocuments I think.
MyMongooseCollection.map(function(item){
return item.toObject();
}
Tested. He works.
+3
source to share