在下面提供以下对象片段:
var s;
var tab = [];
var myarray= [];
for(var i=0;i<=tab.length-1;i++){
s= "{\"id\":\"" + tab[i][0] + "\",\"ts\":\"" + tab[i][1] + "\",\"lat\":\"" + tab[i][2] + "\",\"lon\":\""+tab[i][3]+"\"}";
myarray.push(s);
}
myarray = [ '{"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}',
'{"id":"id2","ts":"ts2","lat":"lat2","lon":"lon2"}',
'{"id":"id3","ts":"ts3","lat":"lat3","lon":"lon3"}' ]
我想使用mongoose将它保存在mongo数据库中,这是我的代码:
for(var obj in myarray){
var doc = new MyCollection(myarray[obj])
doc.save()
.catch((err=>{console.log(error.message);}))
}
但是我在执行代码时遇到了这个错误:
TypeError: Cannot use 'in' operator to search for '_id' in {"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}
我找不到错误的来源。你能帮帮我吗?
答案 0 :(得分:1)
在myarray中,您使用单引号括起了对象。删除并尝试。你的myarray应该是这样的。
myarray: [ {"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}',
'{"id":"id2","ts":"ts2","lat":"lat2","lon":"lon2"}',
'{"id":"id3","ts":"ts3","lat":"lat3","lon":"lon3"} ];
for(var obj in myarray){
var doc = new MyCollection(myarray[obj])
sigfoxData.save()
.catch((err=>{console.log(error.message);}))
}
答案 1 :(得分:0)
希望这有帮助
var myarray = [ {"id":"id1","ts":"ts1","lat":"lat1","lon":"lon1"}',
'{"id":"id2","ts":"ts2","lat":"lat2","lon":"lon2"}',
'{"id":"id3","ts":"ts3","lat":"lat3","lon":"lon3"} ];
Model.create(myarray, function (err) {
if (err) {
response.send({error: true, message: err});
} else {
response.send({success: true});
}
});
答案 2 :(得分:0)
我通过这样做得到了解决方案:
for(var i=0;i<=tab.length-1;i++){
s= "{\"id\":\"" + tab[i][0] + "\",\"ts\":\"" + tab[i][1] + "\",\"lat\":\"" + tab[i][2] + "\",\"lon\":\""+tab[i][3]+"\"}";
myarray.push(JSON.parse(s));
}
所以我只是解析了s字符串!