use*_*355 5 json asynchronous mongoose node.js
也许我不理解javascript/coffee脚本以及我想但当我这样做时:
that.thing = thing
that.thing.title = "some title"
console.log(that.thing.title)
console.log(JSON.stringify(that.thing)
Run Code Online (Sandbox Code Playgroud)
我得到输出:
一些头衔
{ "CREATION_DATE": "2011-09-09T00:40:03.742Z", "_ ID": "4e6960638ec80519a0000013"}
问题是当我执行stringify时,我似乎失去了title属性(稍后当函数存在时,我似乎有其他有趣的问题,我认为这与'that'和嵌套在多个fxn调用中有关).
(我现在必须做一个丑陋的解决方案,我做那个.thing = {}来解决我的问题.我必须解决的其他问题包括node.js + async + mongoose.find,这都在async.findEach中
当我做
console.log(that.thing.toJSON)
Run Code Online (Sandbox Code Playgroud)
我明白了:
function(){return this.toObject(); }
谢谢.
这是因为Model.find()正在返回一个MongooseDocument.如果您想要一个可以添加属性的纯JavaScript对象,则需要指定"精简"选项:
Model.find().lean().exec(function (err, thing) {
thing.title = "some title";
console.log(JSON.stringify(thing));
});
Run Code Online (Sandbox Code Playgroud)
如果您不需要再次保存thing对象(因为这不是MongooseDocument,不应用getter和setter),这将正常工作.
既然你提到猫鼬,它可能是that.thing一个具有一些特定属性的特殊对象。
有两件事可能会影响这一点。
两者thing实际上都是具有一些可怕逻辑的 getter/setter
或者更有可能thing有一个.toJSON将对象写入 json 的方法,并且您没有增强或删除该方法来使其JSON.stringify工作。
我的默认JSON.stringify调用该.toJSON方法(如果存在)。
所以一个简单的console.log(that.thing.toJSON);应该可以确定你的问题
无论如何,当您想要记录数据并确保它以阻塞方式记录当前数据时,您真正应该做什么。
console.warn(util.inspect(that.thing));
| 归档时间: |
|
| 查看次数: |
15016 次 |
| 最近记录: |