下面的 JSON 是我想保存我的 MongoDB 集合的示例,其中的鍵應用作_id
's.
我只能想到一種非常復雜的方法來做到這一點,我將回圈物件并子回圈嵌套物件并_id
手動插入 's:
const customerObj = await customerDocument.create({ _id: '5434', ...customerColl['5434'] });
我有 10000 這些,所以不能手工完成。
問題
如何使用 Mongoose 將這樣的現有物件保存在集合中?
{
"5434": {
"name": "test 1",
"status": "active",
"address": {
"1467": {
"comment": ""
}
},
"contact": {
"3235": {
"firstname": ""
}
}
},
"6000": {
"name": "test2",
"status": "active",
"address": {
"1467": {
"comment": ""
}
},
"contact": {
"3235": {
"firstname": ""
}
}
}
}
uj5u.com熱心網友回復:
您應該能夠使用 for-in 回圈并像這樣列舉值:
for (const id in customerColl) {
await customerDocument.create({ _id: id, ...customerColl[id] });
}
但是,由于您有 10000 多個物件,這可能會很慢......謝天謝地,貓鼬允許我們批量插入/寫入:
const docs = Object.keys(customerColl) // get the keys... kinda like for-in loop
.map((id) => ({ _id: id, ...customerColl[id] })); // map to docs
await customerDocument.insertMany(docs);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522646.html