我正在使用node.js将数据存储在MongoDB集合中。因为我想使用变量将数据存储在我正在使用对象的正确位置,例如this
我的问题如下:我想将数据推送到2个不同的数组中,一个数组在“温度”中。和“时代”中的数组。通常情况下,应该使用一个$ push并定义所有需要的“推送”,就像我使用$ inc一样。不幸的是,我无法一次推送2个对象,我的代码只推送最后一个对象(在这种情况下为“时间”)。希望有人可以帮助我!
这是我的node.js文件:
var content = 22;
var t = new Date();
var hour = t.getHours();
var minute = t.getMinutes();
var temp = {};
var time = {};
temp["Temperature."+hour]=content;
time["Times."+hour]=minute;
mongodbClient.connect("mongodb://localhost:27017/database1", function(err,d$
if(err){return console.dir(err);}
collection=db.collection("collection1");
collection.update(
{ _id:"S5113N, 424E:20150513" },
{
//Everything works just fine untill:
$push:(temp,time), //Using { } won't work
$set: {"Temperature.TotalAverage": "dif"}, //works
$inc: { //works
"Temperature.Updates": 1,
"Times.Updates": 1
}
}
)
db.close();
这是我的JSON文件:
{ "_id": "S5113N, 424E:20150513",
"I/O": "Indoor",
"Times":{
"0": [],
"1": [],
"2": [],
"3": [],
"4": [],
"5": [],
"6": [],
"7": [],
"8": [],
"9": [],
"10": [],
"11": [],
"12": [],
"13": [],
"14": [],
"15": [],
"16": [],
"17": [],
"18": [],
"19": [],
"20": [],
"21": [],
"22": [],
"23": [],
"Updates": 0
},
"Temperature":{
"0": [],
"1": [],
"2": [],
"3": [],
"4": [],
"5": [],
"6": [],
"7": [],
"8": [],
"9": [],
"10": [],
"11": [],
"12": [],
"13": [],
"14": [],
"15": [],
"16": [],
"17": [],
"18": [],
"19": [],
"20": [],
"21": [],
"22": [],
"23": [],
"Averages": [],
"TotalAverage": 0,
"Updates": 0
}
}
答案 0 :(得分:3)
您的代码无法构建外观的对象,就像$push
您的数据一样:
{
"Temperature.23": 12,
"Times.23": 57
}
只需更改代码即可获得所需的结果:
changes = { }
changes["Temperature."+hour]=content;
changes["Times."+hour]=minute;
然后:
{
$push: changes, // <----
$set: {"Temperature.TotalAverage": "dif"}, //works
...
}