TypeError:db.collection不是函数,不能获取

时间:2016-01-16 13:15:50

标签: node.js mongodb get

我正在尝试从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"
  }
}   

4 个答案:

答案 0 :(得分:2)

incorect语法,你必须读取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 object = {     'some_value':'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);
    });
};

答案 1 :(得分:1)

您只能在文件中声明一次module.exports,因此您应该更改:

在您的database.js文件中:

module.exports.saveBook 

exports.saveBook 

等等

看看这个:https://www.sitepoint.com/understanding-module-exports-exports-node-js/

答案 2 :(得分:0)

在package.json文件夹中找到mongodb内部依赖关系并使用以下值进行更新:

"mongodb": "^2.2.33",

然后运行

npm install

一次。这将解决你的问题。

答案 3 :(得分:0)

确保在package.json文件中的脚本部分添加以下内容

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js",
    "dev": "nodemon server.js",
    "debugger": "DEBUG=*:* npm run dev"
  },