Mongoid:如何将 collection 限制为一个条目?

Mongoid: How do I limit a collection to one entry?

问题::
有没有办法将 table 限制为一个条目?
我想从模型中执行此操作,因此只能创建和修改一个条目。目前我只允许修改 Object.first 条目。我也愿意听取更好的做法。提前致谢


背景::
我是 Mongo 的新手,我找到的唯一信息是创建一个新的 collection。

使用 Mongo DB,您可以使用 Capped Collections.
进行限制 Set limits on mongo db collection

"Mongoid does not provide a mechanism for creating capped collections on the fly - you will need to create these yourself one time up front either with Moped or via the Mongo console."
https://mongoid.github.io/old/en/mongoid/docs/persistence.html

    session.command(create: "name", capped: true, size: 10000000, max: 1000)


根据您要实现的目标,上限集合可能不适合您的用例。在 Capped Collection Documentation 中,它表示:

Capped collections work in a way similar to circular buffers: once a collection fills its allocated space, it makes room for new documents by overwriting the oldest documents in the collection.

如果您使用上限集合然后插入新文档,它只会覆盖现有文档,而不是抛出错误。当然,您可以只插入一个包含更新信息的新文档,而不是覆盖现有文档,但我不确定您是否打算这么做。 (如果这有帮助,您可以在设置 Mongo 数据库实例时通过 Mongo Shell 创建一个上限集合。)

总的来说,在您的应用程序逻辑中强制执行此规则听起来是可行的方法。我还会花一些时间思考您是否真的需要将此信息存储在数据库中——Ruby 单例 class 或某些环境变量是否更适合您的需求?