[英]How to Insert items into multiple Arrays in Node.js & MongoDB
這可能是一個奇怪的問題,但我相信沒有什么是完全不可能的。
我在 MongoDB 中有一個用戶列表,每個用戶除其他外還有當前為空的屬性數組。
在 Excel 表中,我有一個代表每個用戶屬性的數據,我想以編程方式將其插入每個用戶的屬性數組中。
導入 excel 工作表可以快速輕松地填充每個用戶的屬性,這是我遇到的問題。
我已經從用戶和他們購買的屬性中添加了 userId 和 PropeId,因此如下所示識別它們
router.put('/importdata', async (req, res)=>{
// upload queries
const imported = req.files.importdata;
const uploadpath = path.resolve(`public/excel_maneger/uploads/ ${imported.name}`);
if (imported.truncated) {
throw new Error("Uploaded File is too big, should not be morethan 20 MB");
}
await imported.mv(uploadpath);
const file = render.readFile(uploadpath);
const sheets = file.SheetNames;
const data = [];
for (let i = 0; i < sheets.length; i++) {
const sheetname = sheets[i];
const sheetData = render.utils.sheet_to_json(file.Sheets[sheetname]);
sheetData.forEach((item) => {
data.push(item);
});
}
try {
const users = await User.find({role: 'Customer'})
for(let i = 0; i < users.length; i++ ){
data.forEach((d) => {
if(users[i].id == d.id){
User.updateMany(
{},
{
$set: {
properties: {
propeId: d.propeId,
},
},
},
(err, d) => {
if (err) console.log(err);
}
);
}
});
}
} catch (err) {
console.log(err)
}
})
問題是這段代碼用相同的信息更新了數據庫中的每個人(包括非指定用戶),我需要幫助,我正在嘗試將 excel 中的 11,000 個用戶信息導入數據庫
當您更新User.updateMany()
時,您沒有傳入 ID。
它的作用是當if
語句為true
時,它會更新所有用戶,您可以使用findByIdAndUpdate
你也應該使用async/await
。 因為這就是您用來查找用戶的內容
await User.findByIdAndUpdate( users[i]._id,{ $set: { properties: { propeId: d.propeId }}})
我終於想通了我在哪里犯了錯誤,我應該使用 $in: 運算符來根據需要訪問多個 ID。
這是解決方案:
data.forEach((d) => {
User.updateMany(
{ _id: { $in: [d.id] } },
{
$push: {
properties: d.propeId,
},
},
(err, d) => {
if (err) return false;
}
);
});
以上驚人地解決了問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.