简体   繁体   中英

Meteor mongo insert unique document

I have a simple Tags Collection in Meteor. Currently in order to ensure that a user cannot create a duplicate Tag document I do this:

var existingTag = Tags.findOne({name: "userInput"})

If existingTag is undefined then I can go ahead and do the insert.

Is there a better/correct way of doing this utilizing meteor mongodb syntax? Cant seem to find any documentation on this.

Thanks.

A good solution is to create Mongo index at the unique field. That way you'll have the uniqueness validation at Mongo level, as well as performance increase for searches on that field.

Meteor currently doesn't support index creation directly, so you need to manually log in to your database and add your index from there. The command for this is:

db.tags.ensureIndex({name: 1}, {unique: true})

Here and here you can find more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM