mongodb sparse &unique
来源:互联网 发布:nginx访问日志格式 编辑:程序博客网 时间:2024/06/06 19:04
最近在使用mongoose插入文档的时候遇到了一个错误,
错误大致如下:MongoError: E11000 duplicats key error index: xxx$user_1 dup key: { : null}
意思很明显,插入的key对应的value值已经存在,但是疑惑的地方就在于,这个值是null,null为什么会重复?
原因就在于user这个key使用了unique的属性,for exmale:
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属性。
阅读全文
0 0
- mongodb sparse &unique
- Mongodb 稀疏索引 sparse
- MongoDB 稀疏(间隙)索引(Sparse Indexes)
- sparse
- sparse
- Sparse
- MongoDB唯一索引(unique:true)导致的问题
- unique
- unique
- unique()
- unique
- unique()
- sparse-table
- Sparse Matrix
- matlab sparse
- matlab sparse
- sparse representation
- sparse coding
- Redis 探究底层存储结构
- ubuntu 14.04 安装cuda
- OpenCV-将图像缩放并显示
- CircleImageView 圆形imageView(转载)
- 第四周项目5(2)--- 循环双链表应用
- mongodb sparse &unique
- MySQL添加函数或存储过程,步骤
- 斐波那契数
- Linux硬件信息命令大全
- java基础整理
- CodeForces
- SPI详解
- c++20170929
- 网络编程复习(八):Netty解决拆包粘包问题--定长方式