Running Raw/Direct/Native MongoDB Queries Through Mongoose.js

Sometimes it may be necessary (particular when modifying a schema), to bypass mongoose schema constraints and access a mongoose database through the native mongodb driver.
Generally, this is as simple as accessing Model.collection 
However, there is a caveat when running find() queries. All native driver documentation suggests that Model.collection.find({}) should return a cursor, but this is not the case with Mongoose.
Running Model.collection.find({}).toArray(function(err, data){}) will throw an error
TypeError: Cannot call method 'toArray' of undefined
because find() will return undefined
Instead, you must pass a callback to find() which accepts the cursor as the second argument. Here is an example:
Model.collection.find({}, function(err, cursor) {
cursor.toArray(function(err, data){
// process data array
})
})

3 comments:

  1. Thanks for sharing, I just like the valuable info you provide for your articles. I’ll bookmark your weblog and take a look at once more right here regularly. Custom essay writing service will give you opportunity to spend more free time with friends. Visit custom essay writing service

    ReplyDelete
  2. Really such a great post. I aprreciate your post .For more queries related to Microsoft Outlook, you can visit these sites for more info.outlook support

    ReplyDelete
  3. Thank you !!! This saved me a lot of time

    ReplyDelete