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

 继续不插电的名单 发布于 2023-02-05 11:01

我有一个简单的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();  

^工作.即用值更新数据库.截图


//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. (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()无法按预期工作的问题是什么?

1 个回答
  • findOneUsers模型上的方法,而不是user模型实例.它通过回调向调用者提供异步结果:

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

    2023-02-05 11:02 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有