如何在流星应用程序中为mongodb添加两列唯一ID? [英] How can I add a two column unique id to the mongodb in a meteor app?
问题描述
我正在尝试在流星应用程序中的基础mongodb上创建一个两列唯一索引并遇到麻烦。我在流星文档中找不到任何内容。我试过Chrome控制台。我从学期开始尝试,甚至试图将mongod指向/ db / dir里面的.meteor。我试过了
I am trying to create a two column unique index on the underlying mongodb in a meteor app and having trouble. I can't find anything in the meteor docs. I have tried from the chrome console. I have tried from term and even tried to point mongod at the /db/ dir inside .meteor . I have tried
Collection.ensureIndex({first_id:1,another_id:1},{unique:true});
变种。
我希望能够防止meteor app mongo集合上的重复条目。
I want to be able to prevent duplicate entries on a meteor app mongo collection.
想知道是否有人想出这个?
Wondering if anyone has figured this out?
我回答了我自己的问题,这是一个菜鸟。
I answered my own question, what a noob.
我想出来。
-
启动流星服务器
Start meteor server
打开第二终端键入 meteor mongo
然后创建索引...例如,我为thumbsup和thumbsdown类型系统的记录做了这些。
Then create your index...for example I did these for records of thumbsup and thumbsdown type system.
db.thumbsup.ensureIndex({item_id: 1, user_id: 1}, {unique: true})
db.thumbsdown.ensureIndex({item_id: 1, user_id: 1}, {unique: true})
现在,只需要弄清楚一个bootstrap安装设置,当你推送到prod而不是手动时,会创建这些设置。
Now, just gotta figure out a bootstrap install setup that creates these when pushed to prod instead of manually.
推荐答案
根据文档Minimongo目前没有索引。很快就会到来。并且查看Collection上可用的方法,没有 ensureIndex
。
According to the docs "Minimongo currently doesn't have indexes. This will come soon." And looking at the methods available on a Collection, there's no ensureIndex
.
您可以运行 meteor mongo
对于mongo shell并启用索引服务器端,但Collection对象仍然不知道它们。因此,应用程序将允许您向Collection缓存添加多个实例,而在服务器端,其他插入将无提示失败(错误将写入输出)。当您进行硬页面刷新时,应用程序将与服务器重新同步
You can run meteor mongo
for a mongo shell and enable the indexes server-side, but the Collection object still won't know about them. So the app will let you add multiple instances to the Collection cache, while on the server-side the additional inserts will fail silently (errors get written to the output). When you do a hard page refresh, the app will re-sync with server
因此,您现在最好的选择可能是:
So your best bet for now is probably to do something like:
var count = MyCollection.find({first_id: 'foo', another_id: 'bar'}).count()
if (count === 0)
MyCollection.insert({first_id: 'foo', another_id: 'bar'});
这显然不理想,但工作正常。您还可以在服务器上的mongodb中启用索引,因此即使在竞争条件下您也不会实际获得重复记录。
Which is obviously not ideal, but works ok. You could also enable indexing in mongodb on the server, so even in the case of a race condition you won't actually get duplicate records.
这篇关于如何在流星应用程序中为mongodb添加两列唯一ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!