本文介绍了TypeError:db.collection不是一个函数,CAN NOT GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



更新:

 > ; TypeError:无法读取属性< findOne&#39;未定义的< 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;在Layer.handle [作为handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <峰; br> &安培; NBSP; & nbsp;在下一个
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <峰; br> &安培; NBSP; & nbsp;在Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <峰; br> &安培; NBSP; & nbsp;在Layer.handle [作为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;在Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <峰; br> &安培; NBSP; & nbsp;在下一个
> (/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;在Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <峰; br> &安培; NBSP; & nbsp;在下一个
> (/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'); //获取数据库配置文件
var User = require('./app/ models / user'); //获取猫鼬模型
var Products = require('./app/ models / products'); //获取猫鼬模型
var Makeissue = require('./ app / models / makeissue'); //获取mongoose模型
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./ config / database.js');
MongoClient.connect(mongoUrl,函数(err,db){
if(err)throw'连接数据库时出错 - '+ err;
//获取我们的请求参数
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

//登录到控制台
应用程序。使用(morgan('dev'));

//在我们的应用程序中使用护照包
app.use(passport.initialize());

//示例Route(GET http:// localhost:8080)
app.get('/',function(req,res){
res.send('API位于http:// localhost:'+ port +'/ api');
});

//连接数据库
mongoose.connect(config.database);

//通过护照配置
require('./ config / passport')(护照);

//捆绑我们的路线
var apiRoutes = express.Router();


//创建一个新的用户帐户(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 '));
} else {
var newUser = new User({
name:req.body.name,
password:req.body .password,
email:req.body.email
});
//保存用户
newUser.save(function(err){
if(err ){
return res.json({success:false,msg:'Username already exists。'));
}
res.json({success:true,msg:'Successful created新用户。'));
});
}
});
$ b $ //路由认证用户(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 {
//检查密码匹配
user.comparePassword(req.body.password,function(err,isMatch){
if(isMatch&&!err){
//如果找到用户且密码为右创建一个令牌
var token = jwt.encode(user,config.secret);
//返回包含令牌的信息为JSON
res.json({success:true,token: Ĵ WT'+令牌});
} else {
res.send({success:false,msg:'Authentication failed。Passwords password。'});
}
});
}
});
});

apiRoutes.post('/ book',function(req,res){
if(!req.body.title ||!req.body.author)res.status(400 ).send(请为该书发送标题和作者);
else if(!req.body.text)res.status(400).send(请为该书发送一些文本 );
else {
access.saveBook(db,req.body.title,req.body.author,req.body.text,function(err){
if(err)res (服务器错误);
else res.status(201).send(Saved);
});
}
} .status );
$ b $ apiRoutes.get('/ book /:title',function(req,res){
if(!req.param('title'))res.status(400)。发送(请发送正确的标题);
else {
access.findBookByTitle(db,req.param('title'),function(book){
if(!req。 (500).send(Server error);
else res.status(200).send(book);
});
}
});


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

apiRoutes.get('/ resources / productinfo /:name',function(req,res){
if(!req.param('name'))res.status(400 ).send(请发送一个专用名称);
else {
access.findProductsByName(Products,req.param('name'),function(Products){
if(!产品)res.status(500).send(服务器错误);
});
}
});

//创建一个新产品(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:'请传递名称和序列号。'));
} else {
var newProducts = new Products({
name:req.body.name,
serialnumber:req.body.serialnumber
});
//保存产品
newProducts.save(function(err){
if(err){
return res.json({success:false,msg:'Product already exists。' });
}
res.json({success:true,msg:'Successful created new Product。'});
});
}
} );
$ b $ 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
}) ;
//保存产品
newMakeissue.save(function(err){
if(err){
return res.json({success:false,msg:'Post '));
}
res.json({success:true,msg:'Successful created new post。'});
});
}
});







//路由到受限信息(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 $ b $如果(!用户){
返回res.status(403).send({b}},函数(err,user){
if(err)throw err;

成功:false,msg:'认证失败,用户未找到')};
} else {
res.json({success:true,msg:'欢迎在成员区'+ user。 name +'!'});
}
});
} else {
return res.status(403).send({success:false,msg:'No token provided。'});
}
});
$ b $ 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;
}
};


//连接/ api / *
下的api路由app.use('/ api',apiRoutes);
module.exports = apiRoutes;



$ b app.listen(8080,function(){
console.log('listening on 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 =函数(db,title,callback){
db.collection ['text']。findOne({
title:title
},function(err,doc){
if(err ||!doc)callback(null);
else callback(doc.text);
});
};

module.exports.findProductsByName =函数(分贝,姓名,回叫){
db.collection [ '产品'] findOne({
名称:名称
},function(err,doc){
if(err ||!doc)callback(null);
else callback(doc.products);
});
};

和package.json



<$ p $ {
name:firstapp,
main:server.js,
依赖关系:{
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
}
}


解决方案

incorect语法,你必须读取db.collection的属性,但是你调用它。示例:

  db.collection ['products'] !!! 

$ b db.collection ['text']。save({
title:title,
author:author,
text:text
},回调);
};

module.exports.findBookByTitle =函数(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'method result'}
}



您可以读取和设置属性'some_value'例如:

 对象[ 'SOME_VALUE'] //返回 '值' 
object.some_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({$ b $ name:name
} ,函数(err,doc){
if(err || !doc)callback(null);
else callback(doc.products);
});
};


i'm trying to get some data from the apiRoutes.get('/resources/productinfo/:name') and i have this error, i dont know whats going wrong... also the apiRoutes.get('/book/:title') doesnt seems to work! i dont know what am i doing wrong

UPDATED:

>       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)

here is the 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');
            });
    });

and the 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);
    });
};

and the 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"
  }
}
解决方案

incorect syntax, you must read property of db.collection, but you call that. Example:

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({

For example

var object = { 'some_value': 'value', 'some_methid': function(){ return 'method result'}}

You can read and set property 'some_value', for example:

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

// STEP 2

Ok, in your methods of database.js you pass db variable, but this is not of db instance, it is mongoose model, and you must write like this:

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);
    });
};

这篇关于TypeError:db.collection不是一个函数,CAN NOT GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:57