Mongoose/MongoDB result fields appear undefined in Javascript

Solution

You can call the toObject method in order to access the fields. For example:

var itemObject = item.toObject();
console.log(itemObject.title); // "foo"

Why

As you point out that the real fields are stored in the _doc field of the document.

But why console.log(item) => { title: "foo", content: "bar" }?

From the source code of mongoose(document.js), we can find that the toString method of Document call the toObject method. So console.log will show fields ‘correctly’. The source code is shown below:

var inspect = require('util').inspect;

...

/**
 * Helper for console.log
 *
 * @api public
 */
Document.prototype.inspect = function(options) {
  var isPOJO = options &&
    utils.getFunctionName(options.constructor) === 'Object';
  var opts;
  if (isPOJO) {
    opts = options;
  } else if (this.schema.options.toObject) {
    opts = clone(this.schema.options.toObject);
  } else {
    opts = {};
  }
  opts.minimize = false;
  opts.retainKeyOrder = true;
  return this.toObject(opts);
};

/**
 * Helper for console.log
 *
 * @api public
 * @method toString
 */

Document.prototype.toString = function() {
  return inspect(this.inspect());
};

Leave a Comment