【问题标题】:Mongodb - Checking if data exists in collection using Node js driverMongodb - 使用 Node js 驱动程序检查集合中是否存在数据
【发布时间】:2012-10-06 12:41:06
【问题描述】:

如何检查集合中的数据是否存在。我需要确保用户名是唯一的。有什么想法吗?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    最简单的方法是在需要唯一的数据上放置唯一索引。如果您尝试插入具有相同值的新数据,Mongo 将返回错误。此时,您可以根据需要处理错误。

    您可以在http://www.mongodb.org/display/DOCS/Indexes#Indexes-unique%3Atrue 阅读有关唯一索引的更多信息。您可以像使用 Node 驱动程序创建任何其他索引一样创建它们。

    // everyone's username must be unique:
    db.createIndex(userCollection, {username:1}, {unique:true});
    

    【讨论】:

    • 谢谢,这正是我所需要的
    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 2015-12-07
    • 2015-11-01
    • 2012-06-23
    • 1970-01-01
    • 2018-02-27
    • 2017-02-10
    相关资源
    最近更新 更多