Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MongoDB:如何在mongoose模式中使用唯一的可选索引?_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript MongoDB:如何在mongoose模式中使用唯一的可选索引?

Javascript MongoDB:如何在mongoose模式中使用唯一的可选索引?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,这是我的猫鼬模式中的字段: var userSchema = moongoose.Schema({ ... customer_id: { type: Number, trim: true } ... }, { timestamps: true }); 我希望此字段是唯一的,并且还接受来自客户端的内容,如“,null或未定义的 1) 我试过这个: customer_id: { type: Number, trim: true, index: {

这是我的猫鼬模式中的字段:

var userSchema = moongoose.Schema({
  ...
  customer_id: {
    type: Number,
    trim: true
  }
  ...
}, {
  timestamps: true
});
我希望此字段是唯一的,并且还接受来自客户端的内容,如
null
未定义的

1) 我试过这个:

customer_id: {
  type: Number,
  trim: true,
  index: {
    unique: true,
    partialFilterExpression: {customer_id: {$type: 'number'}}
  }
}
2) 还包括:

customer_id: {
  type: Number,
  trim: true,
  index: {
    unique: true,
    partialFilterExpression: {customer_id: {$exists: true}}
  }
}
3) 这是:

customer_id: {
  type: Number,
  trim: true,
  unique: true,
  sparse: true
}
这些不起作用

每次测试之间,我都会重置我的收集,当我添加第二个客户时,仍然会出现409冲突错误

编辑:应该匹配的文档,没有冲突(当前冲突):我有一个id为
customer\u id:11111
的第一个客户。现在我想添加另一个客户,他可以拥有
客户id:22222
客户id:“
客户id:null
,但不能拥有
客户id:11111

MongoDB shell/db版本:3.4.4 猫鼬:4.9.7


有什么想法吗?

您可以更新您的问题,以显示两个本应允许但导致冲突的文档吗?您是否尝试过在客户id密钥上创建索引?像db.users.createIndex({customer\u id:1},{unique:true,partialFilterExpression:{customer\u id:{$type:'number'}}}}}}}?@Astro:我没有像您那样使用任何mongo shell命令,我使用Mlab与Heroku结合使用,并且没有所有访问权限(现在)要使用Mongo shell,还是说这一行必须在代码中实现?是的,您也可以从代码中创建这样的索引,谢谢,但这并没有显示您不希望冲突的冲突内容。