Node.js和JSON.stringify缺less一些来自对象的值/参数

也许我不明白的JavaScript /咖啡脚本以及我想,但是当我这样做:

that.thing = thing that.thing.title = "some title" console.log(that.thing.title) console.log(JSON.stringify(that.thing) 

我得到输出:

一些标题

{ “CREATION_DATE”: “2011-09-09T00:40:03.742Z”, “_ ID”: “4e6960638ec80519a0000013”}

问题是,我似乎失去了标题属性,当我做的string化(后来当function存在,我似乎有其他有趣的问题,我认为必须与'那',这嵌套在多个fxn调用)。

(我现在必须做一个丑陋的解决scheme,我现在在那里解决我的问题。我必须解决的其他问题之前,包括node.js + async + mongoose.find,这是所有内部的async.findEach)

当我做

 console.log(that.thing.toJSON) 

我得到:

函数(){返回this.toObject(); }

谢谢。

这是因为Model.find()正在返回一个MongooseDocument。 如果您想要一个普通的JavaScript对象,您可以添加属性,您需要指定“精益”选项:

 Model.find().lean().exec(function (err, thing) { thing.title = "some title"; console.log(JSON.stringify(thing)); }); 

这将工作得很好,只要你不需要再保存东西对象(因为这不是一个MongooseDocument,没有getters和setter被应用)。

既然你提到mongoose,那可能就是那个that.thing是一个具有特定属性的特殊对象。

有两件事可能会影响到这一点。

这两thing实际上都是一个有一些可怕的逻辑的吸气/安装者

或者更有可能的thing有一个.toJSON方法,写对象到JSON,你没有增加或删除该方法,使JSON.stringify工作。

如果它存在,我的默认JSON.stringify调用.toJSON方法。

所以简单的console.log(that.thing.toJSON); 应该确定你的问题

无论如何,当你想logging数据,并确保它以阻塞的方式logging当前数据时,你真的应该做什么。

console.warn(util.inspect(that.thing));

你看到“function(){return this.toObject();}”,因为toJSON是一个原型函数。

也就是说,console.log(that.thing.toJSON)将打印函数本身,但是console.log(that.thing.toJSON())将打印从函数返回的值。 添加额外的括号将执行该function。

尝试console.log(that.thing.toJSON()),看看你得到你在找什么。