mongoose Model.findOne TypeError:对象没有方法';芬顿';
我有一个简单的node.js代码,它使用mongoose,在保存时可以工作,但不能检索mongoose Model.findOne TypeError:对象没有方法';芬顿';,mongoose,Mongoose,我有一个简单的node.js代码,它使用mongoose,在保存时可以工作,但不能检索 .save()有效,但.findOne()无效 mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/TestMongoose"); UserSchema = new mongoose.Schema({ field: String }); Users = mongoose.model('userauths',
.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();
^工作。i、 e.使用值更新数据库
^抛出错误:
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
^仅返回对象{field:'value'}
console.log(JSON.stringify( Users , null, 40));
^返回未定义的
Users.findOne();
^没有错误,但不返回任何内容。(函数
findOne()
也存在于Users
?但是为什么console.log(…Users..
返回未定义的?)
是什么问题导致findOne()
无法按预期工作?是用户
模型上的方法,而不是用户
模型实例。它通过回调向调用者提供其异步结果:
Users.findOne({field:'value'}, function(err, doc) { ... });
要详细说明当前正确的答案,请注意userSchema.path和userSchema.statics之间的区别——前者使用“this”作为模型实例,而后者中的“this”指模型“类”本身:
Users.findOne();
Users.findOne({field:'value'}, function(err, doc) { ... });
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);
});
}
});
};
};