node.js - mongoose 修复了唯一且稀疏的索引,并且可以采用空值
问题描述
我找到的大多数答案都来自旧帖子,我看到了 Partial Index 但没有关于如何使用它的好例子,当我再次启动 mongoose 时我启动了我的索引,找不到如何设置它以使用 Partial Index 的示例。
// db is read from a config file
mongoose.connect(db.uri, {autoIndex: db.autoIndex, useNewUrlParser: true});
如果我希望像电子邮件这样的属性是可选的并且是唯一的并且被索引,那么问题是当我将其设置更新为空或空白时,即使我强制它未定义并且会导致重复错误。
这是我想出的解决方案,但这是他们更好的方法,这是我的简化模型
let UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
trim: true,
index: {unique: true, sparse: true}
}
});
// this run when creating a new user
UserSchema.pre('save', function (next) {
if (this.email === null || this.email === '') {
this.email = undefined;
}
next();
});
// this runs when updating a user
UserSchema.pre('update', function () {
const update = this.getUpdate();
let fix = {};
if (update.email === null || update.email === '') {
delete this._update.email;
fix.email = true;
}
this.update({}, {$unset: fix});
});
// Also what about findOneAndUpdate method will I need a pre method too
解决方案
在深入挖掘之后,我终于解决了它,使用部分索引并为空字符串的情况设置一个函数,这将引发重复错误,因此空值对于未定义的值可以正常工作,并且将被认为是唯一的
let UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
trim: true,
index: {
unique: true,
partialFilterExpression: {email: {$type: 'string'}},
},
set: v => (v === '' ? null : v)
}
});
推荐阅读
- swift - How can I make a variable take only one of certain values in Swift 5
- python - 使用 OpenCV (putText) 设置文本宽度
- javascript - 下载完成后立即通过操作系统打开下载的文件
- java - 在 Apache Pulsar 中授予命名空间权限
- mongodb - 如何在 Kubernetes 的 postStart 生命周期钩子中延迟执行命令
- powershell - 使用 Azure 自动化 Runbook 将项目添加到 SPO
- bash - 码头工人终端上的“基本名称:缺少操作数”
- r - `$<-.data.frame`(`*tmp*`, marital1, value = numeric(0)) 中的错误:替换有 0 行,数据有 526
- c++ - 使用 Doxygen 在不同文件中注释函数
- javascript - 在控制台中打印数组时长度错误