猫鼬Model.findOne TypeError:对象没有方法'findOne' [英] mongoose Model.findOne TypeError: Object has no method 'findOne'
问题描述
我有一个简单的node.js代码,它使用猫鼬在保存时有效,但无法检索.
I have a simple node.js code that uses mongoose which works when saving but doesn't retrieve.
.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();
^有效.即使用值更新数据库. 屏幕截图
^ works. i.e. updates the database with values. screenshot
//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
?)
^ no error, but doesn't return anything.
(so does the function findOne()
exists in Users
? but so why then does console.log(..Users..
returns undefined
?)
什么可能导致findOne()
无法按预期工作?
What could be the issue causing findOne()
to not work as expected?
推荐答案
findOne
是Users
模型上的方法,而不是user
模型实例上的方法.它通过回调将其异步结果提供给调用方:
findOne
is a method on your Users
model, not your user
model instance. It provides its async results to the caller via callback:
Users.findOne({field:'value'}, function(err, doc) { ... });
这篇关于猫鼬Model.findOne TypeError:对象没有方法'findOne'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!