node.js - MongoDb:如何根据每个字段的值更新多个文档中的字段值?
问题描述
我有许多包含一个字段的文档description
:
const HelpRequestSchema = new Schema({
description: {
type: String,
required: true,
},
});
module.exports = HelpRequest = mongoose.model(
"help_requests",
HelpRequestSchema
);
我写了一个加密字符串的函数:
const encrypt = function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return encrypted.toString("hex");
};
我想在所有现有文档上运行该功能以加密所有description
字段。
为此,我必须检索描述field
值,对其进行加密,然后将其写回对应的文档中。
一个幼稚的解决方案是使用每个文档updateOne
或findOneAndUpdate
与每个文档一起使用,但这不是有效的。
最好的方法是什么?
解决方案
你可以试试
db.help_requests.find().snapshot().forEach(
function (elem) {
db.help_requests.update(
{
_id: elem._id
},
{
$set: {
description: encrypt(elem.description)
}
}
);
}
);
或者
db.help_requests.updateMany(
{},
[
$set: {
description: encrypt($description)
}
]
)
推荐阅读
- java - 使用 RabbitTemplate 发布消息时出现 java.lang.IllegalArgumentException
- c - Optimizing Matrix multiplication in C with Bit Packing
- python - 在 jupyter notebook 中加载数据集
- google-compute-engine - Create firewall exception on Google Compute Engine and connect via telnet
- python-3.x - Python 3.7 boolean indexing *warning* using 'list'
- javascript - 具有初始状态的复选框组
- c# - 以毫秒为单位的不同数字的 TimeSpan 解析问题
- php - MySQL 多重条件类型
- azure - Azure 弹性数据库是否按开发人员收费?
- python - 如何在使用 wxPython 时滚动时更改 wx.Choice?