【问题标题】:JSON.stringify not working for mongoose object in NodeJsJSON.stringify 不适用于 NodeJs 中的猫鼬对象
【发布时间】:2016-04-11 12:40:54
【问题描述】:

我在控制台 mongoose 对象时遇到错误。 这是我的代码:-

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Yea! we are connected.');
});
console.log(JSON.stringify(mongoose));

这是错误信息:-

【问题讨论】:

  • 错误非常明显。为什么还要将 mongoose 对象转换为 JSON?
  • 你想做什么?你试图对模块对象进行字符串化是错误的。
  • 我只是想看看 mongoose 对象中有哪些数据是出口。如果我使用console.log(mongoose) 我得到了结果但不合适。@qqilihq,@Michelem

标签: json node.js mongodb


【解决方案1】:

猫鼬模块内部有这个逻辑

Mongoose.prototype.Mongoose = Mongoose;

它使循环结构(对象自引用)。您不能默认对圆形对象进行字符串化。如果您想使用JSON.stringify,请添加您的自定义逻辑句柄

JSON.stringify(obj,function(k,v){ //logic})

【讨论】:

    【解决方案2】:

    您可能想尝试返回对象的字符串表示形式的 util.inspect(object) 方法:

    var util = require('util');
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/test');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function () {
        console.log('Yea! we are connected.');
    });
    console.log(util.inspect(mongoose, { showHidden: true, depth: null }));
    

    【讨论】:

    • 我可以用肉眼看到整个猫鼬的属性和成员。谢谢@chridam。
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 2015-07-06
    • 2016-09-04
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2013-06-24
    相关资源
    最近更新 更多