我的收藏中有一个名为email的列,其中包含电子邮件地址。现在,我需要更新所有这些电子邮件地址,在电子邮件末尾(@之前)附加_01。基本上,如果电子邮件为[email protected]
,则应将其转换为[email protected]
。我知道我们可以使用updateMany
使用猫鼬更新多个文档,但是要实现我所需要的,我相信我也需要使用某种正则表达式吗?
请尝试这个:
let emails = ['[email protected]', '[email protected]']
let bulkArr = [];
for (const i of emails) {
let newEmail = i.split("@");
newEmail = newEmail[0] + '_01' + '@' + newEmail[1]
bulkArr.push({
updateOne: {
"filter": { email : i },
"update": { '$set': { email : newEmail } }
}
})
}
let updateResult = await MongooseModel.bulkWrite( bulkArr, { ordered : false })
/** Passing { ordered : false } to make sure update op doesn't fail if updating one document in the middle fails, Also bulkWrite returns write result check documentation for more info */
console.log('matchedCount ::', updateResult.matchedCount, 'modifiedCount ::', updateResult.modifiedCount)
Ref: .bulkWrite()