Node.js 使用预保存挂钩时,如何对照DB检查值?
在用户模式中,我想在保存之前检查指定商店的指定电子邮件是否已经存在Node.js 使用预保存挂钩时,如何对照DB检查值?,node.js,mongoose,Node.js,Mongoose,在用户模式中,我想在保存之前检查指定商店的指定电子邮件是否已经存在 var UserSchema = new Schema({ _shop: { type: Schema.Types.ObjectId, ref: 'Shop', required: true }, email: String, //... }); UserSchema.pre('save', function(next) { if (!th
var UserSchema = new Schema({
_shop: {
type: Schema.Types.ObjectId,
ref: 'Shop',
required: true
},
email: String,
//...
});
UserSchema.pre('save', function(next) {
if (!this.isNew) return next();
// How to do use the static method isThatEmailFreeForThisShop here?
});
UserSchema.statics.isThatEmailFreeForThisShop = function(email, shop_id, cb) {
this.find({email: email, _shop: shop_id}, function(err, users) {
// ...
});
});
可能有不同的用户使用相同的电子邮件,只要他们来自不同的商店。
我不知道如何使用静态方法在预保存挂钩。。。
谢谢 您已经在某处创建了一个用户模型实例(我称之为
User
):
因此,是指在用户
型号上可以使用EmailFreeforThisShop
功能:
User.isThatEmailFreeForThisShop(...)
从保存挂钩:
UserSchema.pre('save', function(next) {
if (!this.isNew) return next();
User.isThatEmailFreeForThisShop(this.email, this._shop,
function(err, result) {
if (result) { // found
// do something
return next({ error: "duplicate found" });
}
return next();
});
});
您可能还希望切换到使用预验证,而不是保存
我希望在函数中,IshatEmailFreeforThisShop
在结果被“找到”时调用cb
参数
您可能会使用findOne
(),而不是find
。考虑到仍然存在竞争条件,您需要将其作为复合索引email
和shop\u id
,并将unique
属性设置为true,以防止重复项潜入(然后,您需要处理这样一个事实,即模型实例上的保存
可能会引发错误)
嗯,这比预期的要容易!谢谢你这有见地的答复!我不知道为什么要设置unique属性呢?如果你想让email和shop组合成为一对独特的组合。(这就是您在调用
find
时所做的事情)。
UserSchema.pre('save', function(next) {
if (!this.isNew) return next();
User.isThatEmailFreeForThisShop(this.email, this._shop,
function(err, result) {
if (result) { // found
// do something
return next({ error: "duplicate found" });
}
return next();
});
});
UserSchema.statics.isThatEmailFreeForThisShop = function(email, shop_id, cb) {
this.findOne({email: email, _shop: shop_id}, function(err, user) {
// ...
cb(err, user != null);
});
});