gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:45:39 26 4
gpt4 key购买 nike

我有一个简单的 node.js 代码,它使用 mongoose,它在保存时工作但不检索。
.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();

^ 有效。即用值更新数据库。 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();

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

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

最佳答案

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

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

关于 Mongoose Model.findOne TypeError : Object has no method 'findOne' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20995954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com