gpt4 book ai didi

node.js - mongoose 是否修复了唯一且稀疏且可以采用空值的索引

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:05 25 4
gpt4 key购买 nike

我找到的大多数答案都来自旧帖子,我看到了部分索引,但没有关于如何使用它的好例子,而且当我再次启动 mongoose 时启动我的索引,找不到关于如何将其设置为与部分索引一起使用的示例。

// 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)
}
});

关于node.js - mongoose 是否修复了唯一且稀疏且可以采用空值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com