Search code examples
node.jsmongodbcursormongoose

Cursor mapping and for each not working, mongodb & mongoose


I'm trying to find all documents in a collection with a field thats an array with an element that matches a certain parameter from a request. Ive trued the following but neither method seems to work. I'm using node mongodb and mongoose.

var cursor = db.Item.find({ cats: { $elemMatch: req.params.cat}});
cursor.map( function(myDoc) {console.log("myDoc.name: " + myDoc.name)});

var cursor = db.Item.find({ cats: { $elemMatch: req.params.cat}});
cursor.foreach( function(myDoc) {console.log("myDoc.name: " + myDoc.name)});

The error I am getting is Object # has no method 'forEach'.

Any help would be great! Thanks!


Solution

  • There are a few things wrong here considering you are using Mongoose. You seem to be trying to use the "shell" type syntax, but in mongoose you work of the model definitions

    var itemSchema = new Schema({
        cats: []
    });
    
    var Item = mongoose.model( "Item", itemSchema );
    

    And presuming then that your "cats" array only contains strings such as:

    {
        "cats": [ "fluffy", "mittens", "stripes" ]
    }
    

    Then you issue the query from the "model" object and use the $in operator for matching the selection. Also as this is "node" the results are within a callback and not returned as a "left side" result:

    Item.find({ "cats": { "$in": [req.params.cat] } },function(err,cats) {
        if ( err ) throw err; // handle errors in some way
    
        console.log( JSON.stringify( cats, undefined, 4 ) );
    });
    

    That will simply dump out all results as it is "automagically" transformed into an array. You can of course then use array iterators and transformers just as .forEach() or .map() on the result from here.