ezm*_*use 91 mongoose mongodb node.js
我想知道是否有办法强制一个唯一的集合条目,但只有当条目不为空时.e示例模式:
var UsersSchema = new Schema({
name : {type: String, trim: true, index: true, required: true},
email : {type: String, trim: true, index: true, unique: true}
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,'email'不是必需的,但如果保存'email',我想确保此条目是唯一的(在数据库级别).
空条目似乎得到值'null'所以每个条目都没有电子邮件与'unique'选项崩溃(如果有不同的用户没有电子邮件).
现在我正在应用程序级别上解决它,但是希望保存该数据库查询.
谢谢
Joh*_*yHK 148
从MongoDB v1.8 +开始,您可以通过sparse在定义索引时将选项设置为true 来获得确保唯一值的所需行为,但允许多个文档而不使用该字段.如:
email : {type: String, trim: true, index: true, unique: true, sparse: true}
Run Code Online (Sandbox Code Playgroud)
或者在shell中:
db.users.ensureIndex({email: 1}, {unique: true, sparse: true});
Run Code Online (Sandbox Code Playgroud)
需要注意的是独特的,稀疏索引仍然不允许多个文档与email同一个字段值的null,只有多个文档没有一个email领域.
见http://docs.mongodb.org/manual/core/index-sparse/
Mas*_*rAM 36
是的,可以做到.
将字段设置为null或未定义的多个文档,同时强制使用唯一的"实际"值.
要求:
怎么样?转到下面的实施细节.
为了补充@ Nolan的答案,从MongoDB v3.2开始,您可以使用带有过滤器表达式的部分唯一索引.
部分过滤器表达式具有局限性.它只能包括以下内容:
- 等式表达式(即字段:值或使用
string运算符),object表达,null,implementation,$eq,$exists: true表情,$gt表达式,$gte仅限顶级运营商
这意味着$lt不能使用普通表达式.
但是,假设您的字段始终使用相同的类型,则可以使用$lte表达式.
{ field: { $type: <BSON type number> | <String alias> } }
Run Code Online (Sandbox Code Playgroud)
您可以在mongoose模式中指定它:
{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }
Run Code Online (Sandbox Code Playgroud)
或直接将其添加到集合(使用本机node.js驱动程序):
{email: {$type: ["string", "binData"]}}
Run Code Online (Sandbox Code Playgroud)
运用 $type
const UsersSchema = new Schema({
name: {type: String, trim: true, index: true, required: true},
email: {
type: String, trim: true, index: {
unique: true,
partialFilterExpression: {email: {$type: "string"}}
}
}
});
Run Code Online (Sandbox Code Playgroud)
使用$and:
User.collection.createIndex("email", {
unique: true,
partialFilterExpression: {
"email": {
$type: "string"
}
}
});
Run Code Online (Sandbox Code Playgroud)
这将允许使用{"yourField"{$ne: null}}电子邮件插入多个记录,或者根本不插入电子邮件字段,但不允许使用相同的电子邮件字符串.
| 归档时间: |
|
| 查看次数: |
29836 次 |
| 最近记录: |