我正在尝试在 meteor 应用程序中的基础 mongodb 上创建一个两列唯一索引,但遇到了问题。我在 meteor 文档中找不到任何东西。我已经从 chrome 控制台尝试过。我从 term 开始尝试过,甚至试图将 mongod 指向 .meteor 内的/db/目录。我试过了
Collection.ensureIndex({first_id: 1, another_id: 1}, {unique: true});
变体。
我希望能够防止 meteor 应用程序 mongo 集合中出现重复条目。
想知道是否有人发现了这一点?
我回答了我自己的问题,真是个菜鸟。
我想通了。
启动 meteor 服务器
打开第二个终端并输入 meteor mongo
然后创建您的索引...例如,我为 thumbsup 和 thumbsdown 类型系统的记录做了这些。
db.thumbsup.ensureIndex({item_id: 1, user_id: 1}, {unique: true})
db.thumbsdown.ensureIndex({item_id: 1, user_id: 1}, {unique: true})
现在,只需要找出一个引导安装设置,它会在推送到 prod 而不是手动创建这些设置。
最佳答案
在 Meteor 源代码中搜索,我发现了一个与 ensureIndex 的绑定(bind),称为 _ensureIndex
。
对于单键基本索引,您可以遵循 packages/accounts-base/accounts_server.js
的示例,该示例在 Meteor 上强制使用唯一用户名:
Meteor.users._ensureIndex('username', {unique: 1, sparse: 1});
对于多键“复合”索引:
Collection._ensureIndex({first_id:1, another_id:1}, {unique: 1});
前面的代码,当放置在服务器端时,确保设置了索引。
注意 _ensureIndex 实现警告:
We'll actually design an index API later. For now, we just pass through to Mongo's, but make it synchronous.
https://stackoverflow.com/questions/10167604/
相关文章:
java - 如何直接从 Java 中的 mongodb 查询返回原始 JSON?
excel - NODE.JS: fatal error - JS 分配失败 - 进程内存不足,同时
mongodb - mongoengine - 忽略模式验证的额外字段
mongodb - 如何在 MongoDB 中将子文档展平为根级别?
mongodb - 文档数据库 : Redundant data, 引用等(特别是 MongoDB)
javascript - MongoError,错误 :E11000 duplicate key e
node.js - 在 MongoDB 中删除时自动删除引用对象