Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.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
Node.js 使用预保存挂钩时,如何对照DB检查值?_Node.js_Mongoose - Fatal编程技术网

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