I'm trying to execute a native MongoDB find
query via the collection
property of a Mongoose Model
. I'm not supplying a callback so I expect the find to return a Cursor
object, but it returns undefined
instead. According to the Mongoose docs, the driver being used is accessible via YourModel.collection
and if I switch to purely using the native driver code find
does return a Cursor
so I can't figure out what's going on.
Here's a code snippet that reproduces the problem:
var db = mongoose.connect('localhost', 'test');
var userSchema = new Schema({
username: String,
emailAddress: String
});
var User = mongoose.model('user', userSchema);
var cursor = User.collection.find({});
// cursor will be set to undefined
I've tried to step into the code with node-inspector, but it's not letting me. Any idea what I'm doing wrong?
You can stream query results from MongoDB. You need to call the Query#cursor() function to return an instance of QueryCursor. Iterating through a Mongoose query using async iterators also creates a cursor.
The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.
A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
What are Cursors? In MongoDB parlance, a cursor is an object that you can use to iterate through the results of a query. If you execute a query against a MongoDB server directly, the result is a cursor rather than a bunch of documents.
The native driver methods are all proxied to run on the nextTick so return values from the driver are not returned.
Instead, you can pass a callback and the 2nd arg returned is the cursor.
User.collection.find({}, function (err, cursor) {
//
});
Curious why you need to bypass mongoose?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With