如何在流星应用程序中向 mongodb 添加两列唯一 ID? [英] How can I add a two column unique id to the mongodb in a meteor app?

查看:16
本文介绍了如何在流星应用程序中向 mongodb 添加两列唯一 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在流星应用程序中的底层 mongodb 上创建一个两列唯一索引,但遇到了问题.我在流星文档中找不到任何内容.我已经从 chrome 控制台尝试过.我从 term 开始尝试,甚至尝试将 mongod 指向 .meteor 内的/db/目录.我试过了

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}); 变体.

我希望能够防止流星应用程序 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.

我想通了.

  1. 启动流星服务器

  1. Start meteor server

打开第二个终端并输入meteor mongo

然后创建您的索引...例如,我为拇指向上和拇指向下类型系统的记录做了这些.

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

现在,只需找出一个引导安装设置,在推送到 prod 时创建这些设置,而不是手动创建.

Now, just gotta figure out a bootstrap install setup that creates these when pushed to prod instead of manually.

推荐答案

根据 docs "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.

您可以为 mongo shell 运行 meteor mongo 并启用服务器端索引,但 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆