Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - How can I add a two column unique id to the mongodb in a meteor app?

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

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.

I figured it out.

  1. Start meteor server

  2. Open 2nd terminal and type 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})

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Collection._ensureIndex(index, options)

Searching inside Meteor source code, I found a bind to ensureIndex called _ensureIndex. For single-key basic indexes you can follow the example of packages/accounts-base/accounts_server.js that forces unique usernames on Meteor:

Meteor.users._ensureIndex('username', {unique: 1, sparse: 1});

For multi-key "compound" indexes:

Collection._ensureIndex({first_id:1, another_id:1}, {unique: 1});

The previous code, when placed on the server side, ensures that indexes are set.

Warning

Notice _ensureIndex implementation warning:

We'll actually design an index API later. For now, we just pass through to Mongo's, but make it synchronous.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...