I am new to mongoose and I tried to search a lot in order to convert a mongoose collection into an array but it returns an error that toArray() is not a method.So here is the alternative way I am trying to convert into an array.I am using passport js method for authentication and for that i require all the user information as an array.I am tryin to implement the example given in
https://github.com/jaredhanson/passport-local/blob/master/examples/express3/app.js
to mongoose driven data.
Heres the snippet I am trying to use for converting a mongoose collection into an Array.
ContactProvider.prototype.findByusername=function(callback){
var users=Post.find({});
var user=toObject((JSON.parse(users))) ;
callback(null,user);
};
I got the following error
undefined:1
[object Object]
^
SyntaxError: Unexpected token o
at Object.parse (native)
at ContactProvider.findByusername (/home/r121/Desktop/nilesh/cmarin-MongoDB-Node-Express-Blog-4a5e5e9/postprovider.js:60:26)
at Object.<anonymous> (/home/r121/Desktop/nilesh/cmarin-MongoDB-Node-Express-Blog-4a5e5e9/app.js:138:37)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
How should I return an array of those collections backs.Can anyone please guide me with the syntax?
A simple solution would be to utilize the callback of the .find() method, then calling the toObject() on the returned results. Example
Post.find({}).exec(function(err, o) {
callback(err, o)
});
Edit: Removed redundant toObject() call for reasons mentioned in comments by JohnnyHK