我不能在Node中修改数组

我试图对从mongoose / MongDB查询返回的数据数组进行一些修改。 但是,我似乎无法对数组进行任何更改。 我在这里错过了很明显的东西吗

function stdSend(err, data, res){ if(err){ console.log(err); res.send(err); }else{ console.log('rows returned: ' + data.length); for(var rep=0;rep<data.length;rep++){ var foo = new Date(data[rep].timestamp); console.log(Object.isFrozen(data[rep])); <- false console.log(Object.isSealed(data[rep])); <- false data[rep].test = 'test'; <- test not added to data[rep] data[rep].timestamp = foo; <- timestamp not modified console.dir(data[rep]); } //console.log(data); res.send(data); } } 

正在从Mongoose .exec函数调用stdSend作为callback。 callback工作正常,并将数据提交给Express中的res.send后,数据将传到浏览器。 但是,我想通过在发送数据之前将data []。timestamp值转换为标准date时间值来做一些快速的错误testing。

然而,我试图改变数据值的一切都失败了。 数据[rep] .test ='test'未能向数据添加testing属性,并且尝试修改时间戳也失败。 isFrozen和isSealed都返回false。

任何想法发生了什么?

编辑:我觉得有什么我在这里问的困惑。 我写数据到数据库。 这是从我试图修改的数据库查询返回的对象数组。 返回的对象如下:

 [ { name: 'scishow', timestamp: 1380154343818, funding: 42, subs: 3500 }, { name: 'scishow', timestamp: 1380240748329, funding: 42, subs: 3520 }, { name: 'scishow', timestamp: 1380327152521, funding: 42, subs: 3554 }, { name: 'scishow', timestamp: 1380413558026, funding: 43, subs: 3579 }, { name: 'scishow', timestamp: 1380585807946, funding: 43, subs: 3638 }, { name: 'scishow', timestamp: 1384300959056, funding: 52, subs: 5 }, { name: 'scishow', timestamp: 1384560752617, funding: 53, subs: 5 }, { name: 'scishow', timestamp: 1384646717448, funding: 53, subs: 5 }, { name: 'scishow', timestamp: 1384819280960, funding: 53, subs: 5 }, { name: 'scishow', timestamp: 1385251243369, funding: 53, subs: 5753 }, { name: 'scishow', timestamp: 1385338257810, funding: 53, subs: 5779 } ] 

如果data是Mongoose查询的结果,它不是一个普通的JS对象数组,而是一个文档实例数组。 他们可能看起来像正确的JS对象,但你不能像这样对待他们。

您需要将这些文档转换为正确的JS对象,然后才能更改它们:

 for (var rep = 0; rep < data.length; rep++) { var doc = data[rep].toObject(); var foo = new Date(doc.timestamp); doc.test = 'test'; doc.timestamp = foo; console.dir(doc); } 

或者,您可以将{ strict: false }添加到架构(如@HenryLeubuild议的),并在文档中使用.set()来添加属性:

 data[rep].set('test', 'test'); 

或者不改变你的模式:

 data[rep].set('test', 'test', { strict: false }); 

在你的mongoose模式定义代码中。 尝试使用选项strict: false来启用设置并获取未定义的模式字段。 默认情况下, stricttrue

 var thingSchema = new Schema({name: String, ...}, { strict: false}); 

请参阅有关严格选项的mongoose文档 。