在使用mongoose的mongodb集合中添加带有字符串的电子邮件地址

问题描述 投票:0回答:1

我的收藏中有一个名为email的列,其中包含电子邮件地址。现在,我需要更新所有这些电子邮件地址,在电子邮件末尾(@之前)附加_01。基本上,如果电子邮件为[email protected],则应将其转换为[email protected]。我知道我们可以使用updateMany使用猫鼬更新多个文档,但是要实现我所需要的,我相信我也需要使用某种正则表达式吗?

mongodb mongoose
1个回答
1
投票

请尝试这个:

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()

© www.soinside.com 2019 - 2024. All rights reserved.