Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native driver find from Mongoose model not returning Cursor

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?

like image 417
JohnnyHK Avatar asked May 14 '12 18:05

JohnnyHK


People also ask

Does Mongoose .find return a cursor?

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.

What does model find () return in Mongoose?

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.

What is the difference between a Mongoose schema and model?

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 is cursor in Mongoose?

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.


1 Answers

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?

like image 100
aaronheckmann Avatar answered Nov 12 '22 05:11

aaronheckmann