【发布时间】:2021-06-24 15:10:59
【问题描述】:
我有很多包含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,但这并不高效。
最好的方法是什么?
【问题讨论】:
-
如果您使用的是 MongoDB v4.4 或更高版本,请使用 Update with Pipeline 和
$function。 -
@prasad_ 没有示例可以获取字段的值并在函数中对其进行修改,然后将其返回并保存在文档中
-
有很多使用管道更新的例子。还有一些使用
$function的例子。官方文档有不止一个例子,Stack Overflow 有很多关于 Update with pipeline 的答案(这个功能已经推出超过 2 年了).. -
"从 MongoDB 4.2 开始,您可以使用聚合管道进行更新操作。通过更新操作,聚合管道可以包含以下阶段: $addFields $set $project $unset $replaceRoot $替换为“
-
你不能使用$function
标签: node.js mongodb mongoose nosql mern