mongoose Model.findOne TypeError: Object has no method 'findOne'

后端 未结 2 1047
轻奢々
轻奢々 2021-01-18 17:39

I have a simple node.js code that uses mongoose which works when saving but doesn\'t retrieve.

.save() works, but .findOne() doesn\'t.

2条回答
  •  既然无缘
    2021-01-18 17:48

    To elaborate on the current answer which is correct, notice the difference between userSchema.path and userSchema.statics - the former uses 'this' as the instance of the model, while in the latter 'this' refers to the model "class" itself:

           var userSchema = ...mongoose schema...;
    
           var getUserModel = function () {
                return mongoDB.model('users', userSchema);
            };
    
    
           userSchema.path('email').validate(function (value, cb) {
                    getUserModel().findOne({email: value}, function (err, user) {
                        if (err) {
                            cb(err);
                        }
                        else if(user){  //we found a user in the DB already, so this email has already been registered
                            cb(null,false);
                        }
                        else{
                            cb(null,true)
                        }
                    });
                },'This email address is already taken!');
    
    
         userSchema.statics.findByEmailAndPassword = function (email, password, cb) {
                    this.findOne({email: email}, function (err, user) {
                        if (err) {
                            return cb(err);
                        }
                        else if (!user) {
                            return cb();
                        }
                        else {
                            bcrypt.compare(password, user.passwordHash, function (err, res) {
                                return cb(err, res ? user : null);
                            });
                        }
    
                    });
    
                };
    
            };
    

提交回复
热议问题