类型错误:db.collection 不是函数,无法获取

2023-12-27

我正在尝试从中获取一些数据apiRoutes.get('/resources/productinfo/:name')我有这个错误,我不知道出了什么问题......还有apiRoutes.get('/book/:title')似乎不起作用!我不知道我做错了什么

更新:

>       TypeError: Cannot read property &#39;findOne&#39; of undefined <br> &nbsp; &nbsp;at Object.module.exports.findBookByTitle
> (/home/themis/firstapp/api/config/database.js:22:26) <br> &nbsp;
> &nbsp;at /home/themis/firstapp/api/server.js:109:22 <br> &nbsp;
> &nbsp;at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> &nbsp; &nbsp;at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br> &nbsp; &nbsp;at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br> &nbsp; &nbsp;at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> &nbsp; &nbsp;at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br> &nbsp; &nbsp;at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:331:14)
> <br> &nbsp; &nbsp;at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:347:14)
> <br> &nbsp; &nbsp;at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:391:3)
> <br> &nbsp; &nbsp;at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br> &nbsp; &nbsp;at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> &nbsp; &nbsp;at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> &nbsp; &nbsp;at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> &nbsp; &nbsp;at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> &nbsp; &nbsp;at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)

这是server.js

  var express     = require('express');
        MongoClient = require('mongodb').MongoClient,
        app = express(),
        mongoUrl = 'mongodb://localhost:27017/firstapp';
    var bodyParser  = require('body-parser');
    var morgan      = require('morgan');
    var mongoose    = require('mongoose');
    var passport    = require('passport');
    var redisClient = require('redis').createClient;
    var redis       = redisClient(6379, 'localhost');
    var config      = require('./config/database'); // get db config file
    var User        = require('./app/models/user'); // get the mongoose model
    var Products    = require('./app/models/products'); //get the mongoose model
    var Makeissue   = require('./app/models/makeissue'); //get the mongoose model
    var port        = process.env.PORT || 8080;
    var jwt         = require('jwt-simple');
    var access      = require('./config/database.js'); 
    MongoClient.connect(mongoUrl, function(err, db) {
        if (err) throw 'Error connecting to database - ' + err;
            // get our request parameters
            app.use(bodyParser.urlencoded({ extended: false }));
            app.use(bodyParser.json());

            // log to console
            app.use(morgan('dev'));

            // Use the passport package in our application
            app.use(passport.initialize());

            // demo Route (GET http://localhost:8080)
            app.get('/', function(req, res) {
                  res.send('The API is at http://localhost:' + port + '/api');
            });

            // connect to database
            mongoose.connect(config.database);

            // pass passport for configuration
            require('./config/passport')(passport);

            // bundle our routes
            var apiRoutes = express.Router();


            // create a new user account (POST http://localhost:8080/api/signup)
            apiRoutes.post('/signup', function(req, res) {
              if (!req.body.name || !req.body.password || !req.body.email) {
                res.json({success: false, msg: 'Please pass name and password and email.'});
              } else {
                var newUser = new User({
                  name: req.body.name,
                  password: req.body.password,
                  email: req.body.email
                });
                // save the user
                newUser.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Username already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new user.'});
                });
              }
            });

            // route to authenticate a user (POST http://localhost:8080/api/authenticate)
            apiRoutes.post('/authenticate', function(req, res) {
              User.findOne({
                name: req.body.name
              }, function(err, user) {
                if (err) throw err;

                if (!user) {
                  res.send({success: false, msg: 'Authentication failed. User not found.'});
                } else {
                  // check if password matches
                  user.comparePassword(req.body.password, function (err, isMatch) {
                    if (isMatch && !err) {
                      // if user is found and password is right create a token
                      var token = jwt.encode(user, config.secret);
                      // return the information including token as JSON
                      res.json({success: true, token: 'JWT ' + token});
                    } else {
                      res.send({success: false, msg: 'Authentication failed. Wrong password.'});
                    }
                  });
                }
              });
            });

            apiRoutes.post('/book', function (req, res) {
                    if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
                    else if (!req.body.text) res.status(400).send("Please send some text for the book");
                    else {
                        access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
                            if (err) res.status(500).send("Server error");
                            else res.status(201).send("Saved");
                        });
                    }
                });

             apiRoutes.get('/book/:title', function (req, res) {
                    if (!req.param('title')) res.status(400).send("Please send a proper title");
                    else {
                        access.findBookByTitle(db, req.param('title'), function (book) {
                            if (!req.body.text) res.status(500).send("Server error");
                            else res.status(200).send(book);
                        });
                    }
                });



            apiRoutes.get('/productinfo' , function(req, res, next) {
                Products.find( function (err, result) {
                if (err) return console.error(err);
                  res.json(result);
              });
            });

             apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
                if (!req.param('name')) res.status(400).send("Please send a proper name");
                else{
                  access.findProductsByName(Products, req.param('name'), function(Products) {
                      if (!products) res.status(500).send("server error");
                        });
                    }
                 });

            // create a new Product (POST http://localhost:8080/api/productsignup)
            apiRoutes.post('/resources/productsignup', function(req, res) {
              if (!req.body.name || !req.body.serialnumber) {
                res.json({success: false, msg: 'Please pass name and serial number.'});
                } else {
                var newProducts = new Products({
                  name: req.body.name,
                  serialnumber: req.body.serialnumber     
                });
                // save the Product
                newProducts.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Product already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new Product.'});
                });
              }
            });

            apiRoutes.post('/resources/createpost', function(req, res) {
              if (!req.body.issue) {
                res.json({success: false, msg: 'Please pass a issue.'});
                } else {
                var newMakeissue = new Makeissue({
                  issue: req.body.issue    
                });
                // save the Product
                newMakeissue.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Post already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new post.'});
                });
              }
            });







            // route to a restricted info (GET http://localhost:8080/api/memberinfo)
            apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
              var token = getToken(req.headers);
              if (token) {
                var decoded = jwt.decode(token, config.secret);
                User.findOne({
                  name: decoded.name
                }, function(err, user) {
                    if (err) throw err;

                    if (!user) {
                      return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
                    } else {
                      res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
                    }
                });
              } else {
                return res.status(403).send({success: false, msg: 'No token provided.'});
              }
            });

            getToken = function (headers) {
              if (headers && headers.authorization) {
                var parted = headers.authorization.split(' ');
                if (parted.length === 2) {
                  return parted[1];
                } else {
                  return null;
                }
              } else {
                return null;
              }
            };


            // connect the api routes under /api/*
            app.use('/api', apiRoutes);
            module.exports = apiRoutes;




            app.listen(8080, function() {
                console.log('listening on port 8080');
            });
    });

和database.js

module.exports = {
  'secret': 'di.ionio.gr',
  'database': 'mongodb://localhost/firstapp'
};

module.exports.saveBook = function (db, title, author, text, callback) {
    db.collection['text'].save({
        title: title,
        author: author,
        text: text
    }, callback);
};

module.exports.findBookByTitle = function (db, title, callback) {
    db.collection['text'].findOne({
        title: title
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.text);
    });
};

module.exports.findProductsByName = function (db, name, callback) {
    db.collection['products'].findOne({
        name: name
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.products);
    });
};

和 package.json

{
  "name": "firstapp",
  "main": "server.js",
  "dependencies": {
    "bcrypt": "^0.8.5",
    "body-parser": "~1.9.2",
    "express": "~4.9.8",
    "jwt-simple": "^0.3.1",
    "mongoose": "~4.2.4",
    "mongodb" : "~1.2.5",
    "morgan": "~1.5.0",
    "passport": "^0.3.0",
    "passport-jwt": "^1.2.1",
    "redis": "~0.10.1"
  }
}   

语法不正确,您必须读取 db.collection 的属性,但您调用它。例子:

db.collection['products']!!!


db.collection['text'].save({
        title: title,
        author: author,
        text: text
    }, callback);
};

module.exports.findBookByTitle = function (db, title, callback) {
    db.collection['text'].findOne({
        title: title
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.text);
    });
};

module.exports.findProductsByName = function (db, name, callback) {
    db.collection['products'].findOne({

例如

var 对象 = { 'some_value': '值', 'some_methid': function(){ return '方法结果'} }

您可以读取并设置属性“some_value”,例如:

object['some_value'] // return 'value'
object.some_value // return 'value'

// 第2步

好的,在你的database.js方法中你传递了db变量,但这不是db实例,它是mongoose模型,你必须这样写:

module.exports.findBookByTitle = function (model, title, callback) {
    model.findOne({
        title: title
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.text);
    });
};

module.exports.findProductsByName = function (model, name, callback) {
    model.findOne({
        name: name
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.products);
    });
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型错误:db.collection 不是函数,无法获取 的相关文章

随机推荐

  • 使用Python从屏幕捕获视频数据

    有没有办法使用Python 也许使用OpenCV或PIL 连续抓取整个或部分屏幕的帧 至少以15 fps或更高的速度 我见过用其他语言完成的 所以理论上它应该是可能的 我不需要将图像数据保存到文件中 实际上 我只是希望它输出一个包含原始 R
  • Typescript 能够进行简单的函数组合吗?

    Typescript 能够进行简单的函数组合吗 我写出了以下用于测试的 compose map 和 filter 的基本实现 下面先设置类型和功能 然后再实现 javascript 似乎没问题 但打字稿显示误报compose用来 具体来说
  • 使用Remoting时如何在.NET3.5中使用App.config而不需要在App.config中添加Remoting相关配置?

    我正在尝试将 App config 用于托管远程处理并在 NET3 5 中开发的 Windows 服务应用程序 在该 App config 中 我想保留一些将在整个解决方案中使用的值 我没有向其中添加远程关系配置内容 但是在运行应用程序时
  • TypeORM 中 .limit() 和 .take() 之间的区别

    我对具有相似目的的不同 TypeORM 方法感到困惑 来自 TypeORM 文档 take 分页限制 设置要获取的最大实体数 skip 分页偏移量 设置要跳过的实体数量 我不太理解 分页限制 偏移 的含义 但是 不幸的是 我找不到任何有关区
  • 如何在FMX2中直接访问TBitmap像素(TBitmap.ScanLine替换)?

    The FMX Types TBitmap http docwiki embarcadero com Libraries XE2 en FMX Types TBitmap类有ScanLine http docwiki embarcadero
  • 如何设计反应制表符表的样式?

    任何人都可以向我提供一些有关如何设计反应制表符表样式的信息吗 我一直在尝试更改标题颜色 边框等 但徒劳无功 我只在文档中找到类名 例如className table bordered table striped 但这对我没有帮助 我想创建自
  • 如何让 Monodevelop 重新使用英语作为其语言

    我不知道这是怎么发生的 但是当我启动 Monodevelop 时 菜单突然以英语以外的语言出现 我尝试重新安装应用程序以及手动删除库下其他目录中的工件 没有运气 重新安装后 它仍然以另一种语言加载 您可以在选项 首选项对话框下更改语言 对我
  • 随机化框中的 (x,y,z) 坐标

    我对 python 相当陌生 在我当前的任务中 它研究的是 3D 粒子 问题的第一部分要求创建一个程序 将相同的 不重叠的粒子放入立方晶格中 所以我下面的代码只是迭代所有可能的组合 将其放入 XYZ 文件中 xyz 文件的格式如下 1000
  • 用随机数据填充对象的 C# 库[关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我想用随机数据填充我的对象 用于测试目的 是否有库可以做到这一点 某种反射方法 它将遍历对象图并初始化原
  • %CPU 列和负载在顶部

    我的一个 C 应用程序在顶部显示非常高的 CPU 但负载却相当低 myapp 总是占用 30 左右 显示在 top 命令的最顶部 但负载总是像 0 00 所以我很困惑负载和 CPU 列之间有什么区别 top 14 09 54 up 62 d
  • Jetpack Compose BottomNavBar 标签重叠 图标

    我试图实现 jetpack compose 底部导航栏 但我遇到了这个问题 每当标签没有足够的空间时 它就会与图标重叠 我错过了什么吗 有没有自动截断或缩小文本之类的解决方案 compose version 1 0 0 beta09 My
  • pyinstaller-frozen .exe 的“tcl\encoding\ascii.enc 无法提取” - Windows

    使用 pyinstaller 冻结为 exe 的 Python 2 7 脚本已在许多不同 Windows 网络上的许多用户成功运行了几个月 今天早上 一个 Windows 网络上的一组用户 并且只有这三个用户 并且只有这个办公室 之前已成功
  • JavaScript Cookie

    我有该域的 cookie forum mywebsite com并为 mywebsite com 是否可以读取 cookie mywebsite com带有 javascript 的域forum mywebsite com地点 是的 你应该
  • 在控制台中收到大量“内容安全策略”警告 (Firefox)

    我正在使用 Firefox 并且在控制台中收到很多 内容安全策略 警告 包括 内容安全策略 页面的设置阻止加载内联资源 script src and 内容安全策略 忽略 script src 或 style src 中的 unsafe in
  • 如何在 Go 中发送带附件的电子邮件

    我找到了这个库 并设法在空电子邮件中发送附件 但没有合并文本和附件 https github com sloonz go mime message https github com sloonz go mime message 如何做呢 我
  • Android 应用程序可以将自己呈现为(虚拟)Matter 设备吗?

    是否可以创建一个将自身呈现为 Matter 设备的 Android 应用程序 例如温度计 有示例代码吗 Android 应用程序可能无法做到这一点 因为它无法始终按需监听外部通信 您可以寻找在 Android 系统上运行本地服务器并以这种方
  • 如何控制 Android 工具栏中的菜单位置

    我想改变 android xml 代码中膨胀菜单项的重力 但我找不到任何属性来解决问题 我想要其中的一个项目left侧面和另一个项目right角的一侧在Toolbar 你们有什么想法吗 这是我现在的状态 这是我的菜单 xml menu me
  • rstudio 到命令行 R 的不同库路径 (`$R_LIBS_USER`)

    我正在尝试找出为什么我的 libPath命令行 R 和 RStudio 之间的不同Desktop 注 这是not的副本这个问题 https stackoverflow com questions 7129213 r libpaths dif
  • 如何在 Haskell 的 GI-Gtk 中将 Widget 转换为 Label?

    我有这个示例代码 其中有一个包含 ListBoxRows 的 ListBox 而 ListBoxRows 又包含一个 Label 当我单击 ListBox 时 我得到一个 ListBoxRow 到目前为止 一切都很好 当我想与 ListBo
  • 类型错误:db.collection 不是函数,无法获取

    我正在尝试从中获取一些数据apiRoutes get resources productinfo name 我有这个错误 我不知道出了什么问题 还有apiRoutes get book title 似乎不起作用 我不知道我做错了什么 更新