【问题标题】:MongoDb: How to update a field value in many documents based on the value of each field?MongoDb:如何根据每个字段的值更新多个文档中的字段值?
【发布时间】: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 值,对其进行加密,然后将其写回对应的文档中。

一个简单的解决方案是对每个文档使用updateOnefindOneAndUpdate,但这并不高效。
最好的方法是什么?

【问题讨论】:

  • 如果您使用的是 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


【解决方案1】:

你可以试试

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

【讨论】:

  • 第一个:TypeError: HelpRequest.find(...).snapshot(...).forEach is not a function
  • 第二个:描述未定义
猜你喜欢
  • 2022-12-20
  • 1970-01-01
  • 2013-07-13
  • 2012-02-20
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多