使用mongoose将单个文档保留在mongoDB集合中 [英] Keep a single document in mongoDB collection using mongoose
问题描述
我创建了一个集合,但是应该在其中保留一个文档. 如何确保猫鼬模式中只有一个文档?
I created a collection but that one should keep a single document inside. How do I ensure that there is a single document in mongoose schema?
推荐答案
您可以创建封顶"集合,可以在其中设置文档限制,也可以在其中存储文档.
You can create "capped" collections, where you can set limit of documents, you can store in it.
但是,这不会阻止添加另一个文档(不确定,是否需要该功能)-如果添加另一个文档,则旧文档将被删除.
It does not however prevent adding another document (not sure, if you need that functionality) - if you add another document, the old one would be deleted.
db.createCollection('mycappedcol',{capped: true, size:999999, max:1})
您也不能从加盖的收藏夹中删除文档,只能将它们替换为新的收藏夹或删除整个收藏夹.
Also you cant delete documents from capped collections, you can only replace them with new ones or drop the whole collection.
PS:在设置上限的集合中,您必须指定大小(以字节为单位),这也是一个限制(集合不能大于指定的大小).如果您不关心大小,而只关心限制,则只需将大小设置为足够大即可.
PS : In capped collections, you have to specify size in bytes, which is also a limit (collection cant be bigger than specified size). If you do not care about size, but you care only about limit, just set size big enough.
这篇关于使用mongoose将单个文档保留在mongoDB集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!