mongoose模型Model.findOne TypeError: 对象没有方法'findOne'。

5

我有一个使用mongoose的简单node.js代码,保存操作是有效的,但是检索操作无效。

.save()有效,但.findOne()无效。

mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/TestMongoose");
UserSchema = new mongoose.Schema({
    field: String
    });
Users = mongoose.model('userauths', UserSchema);

user = new Users({
    field: 'value'
    });

//user.save();  

^工作。也就是更新数据库值。截图


//user.findOne({field:'value'},function(err,value){});

^ 抛出错误:

user.findOne({field:'value'},function(err,value){});
     ^
TypeError: Object { field: 'value', _id: 52cd521ea34280f812000001 } has no method 'findOne'
    at Object.<anonymous> (C:\localhost\nodeTest\z.js:16:6)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

console.log(JSON.stringify(   user    , null, 40));

^ 返回的仅仅是对象 {field: 'value'}

console.log(JSON.stringify(   Users   , null, 40));

^ 返回 undefined

Users.findOne();

^ 没有错误,但是没有返回任何东西。
Users 中是否存在 findOne() 函数?但为什么 console.log(..Users.. 返回 undefined?)

导致 findOne() 无法按预期工作的问题可能是什么?

2个回答

9

findOne是在您的Users模型上的一个方法,而不是在user模型实例上。它通过回调向调用者提供异步结果:

Users.findOne({field:'value'}, function(err, doc) { ... });

1
为了阐述目前的正确答案,需要注意userSchema.path和userSchema.statics之间的区别 - 前者使用'this'作为模型实例,而后者中的'this'指的是模型“类”本身。
       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);
                        });
                    }

                });

            };

        };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接