首页 > 解决方案 > 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值,对其进行加密,然后将其写回对应的文档中。

一个幼稚的解决方案是使用每个文档updateOnefindOneAndUpdate与每个文档一起使用,但这不是有效的。
最好的方法是什么?

标签: node.jsmongodbmongoosenosqlmern

解决方案


你可以试试

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)
                }
    ]
)

推荐阅读