鍍金池/ 問(wèn)答/數(shù)據(jù)庫(kù)  HTML/ console.log 會(huì)調(diào)用 mongoose 文檔的 toObject 方法

console.log 會(huì)調(diào)用 mongoose 文檔的 toObject 方法?

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
const A = mongoose.model('A', new mongoose.Schema({name: String}))

A.create({name: 'aaa'}, (err, doc) => {
  console.log(doc) // { _id: 5ae424bdcc21a02b700f9342, name: 'aaa', __v: 0 }
  doc.toObject = o => 0
  console.log(doc) // 0
})
// ------------------------------------
A.create({name: 'aaa'}, (err, doc) => {
  console.log(doc) // { _id: 5ae42509ae09661d681416f8, name: 'aaa', __v: 0 }
  doc.toObject = 0
  console.log(doc) // 報(bào)錯(cuò): TypeError: this.toObject is not a function
})
回答
編輯回答
嫑吢丕

是調(diào)用了toString。

Document.prototype.inspect = function(options) {
  var isPOJO = options &&
    utils.getFunctionName(options.constructor) === 'Object';
  var opts;
  if (isPOJO) {
    opts = options;
    opts.minimize = false;
  }
  return this.toObject(opts);
};

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

Document.prototype.toString = function() {
  return inspect(this.inspect());
};
2018年2月22日 17:47