我知道这已经被问过了,但是我似乎找不到答案,我想从isiuser数组中获取no_anggota,nama_lahir和tgl_lahir,我想插入到ZZZ中。
isiseat = [
[{ x: 0, y: 0, val: 1 },
{ x: 1, y: 0, val: 1 },
{ x: 2, y: 0, val: 1 }]
[{ x: 0, y: 1, val: 1 },
{ x: 1, y: 1, val: 1 },
{ x: 2, y: 1, val: 1 }]
[{ x: 0, y: 2, val: 1 },
{ x: 1, y: 2, val: 1 },
{ x: 2, y: 2, val: 1 }]
];
isiuser = [ { no_anggota: '12345', nama_lahir: ' Agus dwi', tgl_lahir: '04-09-2018'},
{ no_anggota: '12345', nama_lahir: 'Septano', tgl_lahir: '15-08-2018'},
{ no_anggota: '12345', nama_lahir: 'Septian putra', tgl_lahir: '15-08-2018'}
];
isiseat.forEach((item1) => {
item1.forEach((item2) => {
var detaildata = {};
detaildata.x = item2.x
detaildata.y = item2.y
detaildata.val = item2.val
detaildata.no_anggota = 'ZZZ'
detaildata.nama_lahir = 'ZZZ'
detaildata.tgl_lahir = 'ZZZ'
detaildata.jadwal = req.body.jadwal
detaildata.section = req.body.section
var savedata = new DetailBooking(detaildata);
savedata.save()
})
});
答案 0 :(得分:0)
您可以使用批量插入bulk insert
var dataArray = [];
var isiseat = [
[
{ x: 0, y: 0, val: 1 },
{ x: 1, y: 0, val: 1 },
{ x: 2, y: 0, val: 1 }
],
[
{ x: 0, y: 1, val: 1 },
{ x: 1, y: 1, val: 1 },
{ x: 2, y: 1, val: 1 }
],
[
{ x: 0, y: 2, val: 1 },
{ x: 1, y: 2, val: 1 },
{ x: 2, y: 2, val: 1 }
]
]
var bulk = db.items.initializeUnorderedBulkOp();
isiseat.forEach((item1) => {
item1.forEach((item2) => {
var detaildata = {};
detaildata.x = item2.x
detaildata.y = item2.y
detaildata.val = item2.val
detaildata.no_anggota = 'ZZZ'
detaildata.nama_lahir = 'ZZZ'
detaildata.tgl_lahir = 'ZZZ'
detaildata.jadwal = 'sssss'
detaildata.section = 'sssssss'
bulk.insert(detaildata);
})
});
bulk.execute();
我保存的数据看起来像这样
{
"_id" : ObjectId("5b61aab063727f69dc5ad1b8"),
"x" : 0.0,
"y" : 0.0,
"val" : 1.0,
"no_anggota" : "ZZZ",
"nama_lahir" : "ZZZ",
"tgl_lahir" : "ZZZ",
"jadwal" : "sssss",
"section" : "sssssss"
}
{
"_id" : ObjectId("5b61aab063727f69dc5ad1b9"),
"x" : 1.0,
"y" : 0.0,
"val" : 1.0,
"no_anggota" : "ZZZ",
"nama_lahir" : "ZZZ",
"tgl_lahir" : "ZZZ",
"jadwal" : "sssss",
"section" : "sssssss"
}
答案 1 :(得分:0)
如果isiseat
和isiuser
数组的长度相同,则可以将index参数传递给forEach
函数。 (See "Loop through an two arrays simultaneously")
因此,您可以将索引传递给第一个forEach
函数:
// Index passed here
isiseat.forEach((item1, index) => {
item1.forEach((item2) => {
var detaildata = {
x: item2.x,
y: item2.y,
val: item2.val,
// ...And then access the `isiuser` array accordingly
no_anggota: isiuser[index].no_anggota,
nama_lahir: isiuser[index].nama_lahir,
tgl_lahir: isiuser[index].tgl_lahir,
jadwal: req.body.jadwal,
section: req.body.section
};
// console.log to see results
console.log(detaildata)
var savedata = new DetailBooking(detaildata);
savedata.save()
})
});