mongodb sparse &unique

最近在使用mongoose插入文档的时候遇到了一个错误,

错误大致如下:MongoError: E11000 duplicats key error index: xxx$user_1 dup key: { : null}

意思很明显,插入的key对应的value值已经存在,但是疑惑的地方就在于,这个值是null,null为什么会重复?

原因就在于user这个key使用了unique的属性,for example:

    let schema = new Schema({

         user: { type: String, unique: true }

    });

当创建文档的时候如果不添加user这个key,就会被赋一个默认值null,而这个null只能存在一个,再次创建一个user为null的时候就会报上面的错误。

难道没有解决办法了吗?不,聪明的mongodb考虑到了,于是提供了sparse属性,这两个搭配使用就可以解决这个问题。

mongodb sparse

官方文档:An index that is both sparse and unique prevents collection from having documents with duplicate values for a field but allows multiple documents that omit the key.

于是这样使用:

    let schema = new Schema({

         user: { type: String, unique: true, sparse: true }

    });

如果key不是必须唯一的建议不使用unique属性。

你可能感兴趣的:(mongodb sparse &unique)