Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I have written the following code to get the number of students per locality: 

var mongoose = require('mongoose');

var schema = mongoose.Schema;

var studentSchema = new mongoose.Schema(

{

 "name":String,

 "address" :{

     "locality":String

  }

});

module.exports = mongoose.model('Student', studentSchema);

The following is the Node.js code:

var Student = require('../../../models/Student');

module.exports.getStudentsBasedOnLocality = function(){

var o = {};

o.map = function () {

    emit(Student.address.locality, 1)

}

o.reduce = function (k, vals) {

    return vals.length

}

Student.collection.mapReduce(o, function (err, results) {

    if(err) throw err;

    console.log(results)

})

};

After implementing the above code, I am getting the following error:

TypeError:

Cannot read property 'out' of undefined

at Collection.mapReduce (C:\***\node_modules\mongodb\lib\collection.js:2961:21)

at NativeCollection.(anonymous function) [as mapReduce] (C:\***\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:136:28) 

1 Answer

0 votes
by (107k points)
edited by

I think you are calling the mapreduce() on the collection property rather than calling on the model. Because in MongoDB, in collection property, you have to have an extra object as a parameter with the out property which is not possible in your case so try to call the mapreduce() function directly on the model. Refer to the following code:

var Student = require('../../../models/Student');

module.exports.getStudentsBasedOnLocality = function(){

    var o = {},

        self = this;

    o.map = function () {

        emit(this.address.locality, 1)

    };

    o.reduce = function (k, vals) {

        return vals.length

    };

    Student.mapReduce(o, function (err, results) {

        if(err) throw err;

        console.log(results)

    });

};

To help you gain a better understanding, here is a Full Stack Developer Certification Course provided by Intellipaat. 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...