如何使一个字段在MongoDB中创建后成为不可变的?

时间:2022-09-12 08:52:50

Use case: I'm writing a backend using MongoDB (and Flask). At the moment this is not using any ORM like Mongoose/Mongothon. I'd like to store the _id of the user which created each document in the document. I'd like it to be impossible to modify that field after creation. The backend currently allows arbitrary updates using (essentially) collection.update_one({"_id": oid}, {"$set": request.json})

用例:我正在使用MongoDB(和Flask)编写一个后端。目前还没有使用任何ORM,比如Mongoose/Mongothon。我想存储创建文档中的每个文档的用户的_id。我希望在创建后不可能修改该字段。后端当前允许使用(本质上)集合进行任意更新。update_one({ " _id ":oid },{“美元”:request.json })

I could filter out the _creator_id field from request.json (something like del request.json["_creator_id"]) but I'm concerned that doesn't cover all possible ways in which the syntax could be modified to cause the field to be updated (hmm, dot notation?). Ideally I'd like a way to make fields write-once in MongoDB itself, but failing that, some bulletproof way to prevent updates of a field in code.

我可以从请求中过滤_creator_id字段。json(类似于del request.json["_creator_id"])),但我担心这并不能涵盖所有可能的方式,可以修改语法以使字段更新(嗯,点表示法?)理想情况下,我希望有一种方法可以使字段在MongoDB中写入一次,但是如果失败,可以使用一些防弹的方法来防止代码中字段的更新。

1 个解决方案

#1


1  

imho there is no know methods to prevent updates inside mongo. As you can control app behavior, then someone will still able to make this update outside the app. Mongo don't have triggers - which in sql world have the possibility to play as a data guards and prevent field changes.

在mongo内部没有防止更新的已知方法。当你可以控制应用程序的行为时,有人仍然可以在应用程序之外进行更新。Mongo没有触发器——在sql世界中,它有可能作为一个数据保护,防止字段变化。

As you re not using ODM, then all you can have is CQRS pattern which will allow you to control app behavior and prevent such updates.

由于您没有使用ODM,那么您所能拥有的就是CQRS模式,它将允许您控制应用程序的行为并防止此类更新。

#1


1  

imho there is no know methods to prevent updates inside mongo. As you can control app behavior, then someone will still able to make this update outside the app. Mongo don't have triggers - which in sql world have the possibility to play as a data guards and prevent field changes.

在mongo内部没有防止更新的已知方法。当你可以控制应用程序的行为时,有人仍然可以在应用程序之外进行更新。Mongo没有触发器——在sql世界中,它有可能作为一个数据保护,防止字段变化。

As you re not using ODM, then all you can have is CQRS pattern which will allow you to control app behavior and prevent such updates.

由于您没有使用ODM,那么您所能拥有的就是CQRS模式,它将允许您控制应用程序的行为并防止此类更新。