为什么mongoose / mongo会在更新时自动对所有数据键进行排序/排序?
例如,这是我设置传递给db的数据:
{ name: 'PM 22',
public: false,
fields: [ 'particles', 'no2', 'no3', 'no4' ],
'$set':
{ 'data.particles': { Array: [Function: Array] },
'data.no2': { Array: [Function: Array] },
'data.no3': { Array: [Function: Array] },
'data.no4': { Array: [Function: Array] },
'data.timestamp': { Array: [Function: Array] } } }
要更新的代码:
dataset.update(updateQuery, function(err, datasetID) {
if (err) {
console.log("Error updating dataset: " + err);
req.session.error = "Update failed, please try again.";
} else {
console.log("Update on dataset: " + datasetID);
req.session.success = "Update successul.";
}
res.redirect("/index");
});
当我检查数据库中的数据时,我得到了这个:
{
"__v" : 0,
"_id" : ObjectId("5773529bdb0dac831f885957"),
"created_at" : ISODate("2016-06-29T04:46:19.553Z"),
"data" : {
"no2" : {},
"no3" : {},
"no4" : {},
"particles" : {},
"timestamp" : {}
},
"entries_number" : 0,
"fields" : [
"particles",
"no2",
"no3",
"no4"
],
"index" : "1IQ0EGIHS",
"name" : "PM 22"
}
如果你看看你知道我的意思:
"data" : {
"no2" : {},
"no3" : {},
"no4" : {},
"particles" : {},
"timestamp" : {}
},
应该是:
"data" : {
"particles" : {},
"no2" : {},
"no3" : {},
"no4" : {},
"timestamp" : {}
},
当我传递这样的数据时:
'$set':
{ 'data.particles': { Array: [Function: Array] },
'data.no2': { Array: [Function: Array] },
'data.no3': { Array: [Function: Array] },
'data.no4': { Array: [Function: Array] },
'data.timestamp': { Array: [Function: Array] }
任何想法为什么以及如何解决这个问题?
修改
var dataset = {
"index" : "9IQ09VRDN",
"name" : "PM 2",
"owner_name" : "xxx",
"read_key" : "16e8da42c5c93f6d53d01931e64aeda7",
"write_key" : "521e838e26aafaefc2d9684959ee1540",
"data" : {
"particles" : [],
"a" : [],
"no3" : [],
"no2" : [],
"timestamp" : [],
},
"entries_number" : 0,
"public" : false,
"fields" : [
"particles",
"no2"
],
"__v" : 0
};
// forEach is a method of array, not of object
for(var obj in dataset.data) {
console.log(obj);
}
我得到了预期的结果,它与javascript本身无关,就像将此问题标记为重复的答案一样:
particles
a
no3
no2
timestamp
这与js本身无关,但与mongo版本无关。
我在2.4。这个问题已在2.6中修复。
https://jira.mongodb.org/browse/SERVER-2592
mongo db update changing the order of object fields
通过将mongo 2.4升级到2.6来解决此问题:
步骤1:导入MongoDB公钥
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
步骤2:使用MongoDB存储库URL生成文件
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
步骤3:使用软件包刷新本地数据库
$ sudo apt-get update
步骤4:在我们的系统上安装最后一个稳定的MongoDB版本和所有必需的软件包
$ sudo apt-get install mongodb-org