1

I am trying to understand mapReduce function, and using it to sort the response in same order as the array of ids provided, according to this question on stackoverflow. Everything works fine when i try to extract books by providing a Array of book titles, but using array of ids it doesn't work. I tried converting ids to ObjectIds but still no hopes. following is data model for books.

const mongoose = require('mongoose');

const BookSchema = mongoose.Schema({

  title: {
    type: 'string',
    required: true
  },

  author: {
    type: 'string'
  },

  coverUrl: {
    type: 'string',
    required: true
  },

  owner: {
    type: 'string',
    required: true
  },

  description: {
    type: 'string'
  }

});

let Book = module.exports = mongoose.model('Book', BookSchema);

code for extracting data is,

// booksIds is an array with only two ids which are strings. 
// three arguments passed to callback (err, docs, stats)

Book.getBooksByIdsWithOrder = function (booksIds, callback) {
  
  // let book_titles = ["The History of Street Art", "A Night In The Woods"];

  booksIds[0] = mongoose.Types.ObjectId(booksIds[0]);
  booksIds[1] = mongoose.Types.ObjectId(booksIds[1]);

  let ask = {}
  ask.map = function () {
    
    var order = inputs.indexOf(this._id);
    emit( order, { doc: this } );
  };
  
  ask.out = {"inline": 1};
  ask.query = { "_id": {"$in": booksIds}};
  ask.scope = {"inputs": booksIds};
  ask.finalize = function (key, value) {
    return value.doc;
  }
  
  Book.mapReduce(ask, callback);
};

Error!

{ MongoError: TypeError: value is null :
@:2:5

    at Function.MongoError.create (/home/user/web_development/bookTradingClub/backend/node_modules/mongodb-core/lib/error.js:31:11)
    at /home/user/web_development/bookTradingClub/backend/node_modules/mongodb-core/lib/connection/pool.js:497:72
    at authenticateStragglers (/home/user/web_development/bookTradingClub/backend/node_modules/mongodb-core/lib/connection/pool.js:443:16)
    at Connection.messageHandler (/home/user/web_development/bookTradingClub/backend/node_modules/mongodb-core/lib/connection/pool.js:477:5)
    at Socket.<anonymous> (/home/user/web_development/bookTradingClub/backend/node_modules/mongodb-core/lib/connection/connection.js:331:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:547:20)
  name: 'MongoError',
  message: 'TypeError: value is null :\n@:2:5\n',
  ok: 0,
  errmsg: 'TypeError: value is null :\n@:2:5\n',
  code: 139,
  codeName: 'JSInterpreterFailure' }
zaheer
  • 320
  • 5
  • 7

0 Answers0