Mongodb nodejs检查是否存在

时间:2016-01-17 11:03:54

标签: node.js mongodb

我正在尝试制作存储产品和用户的API! 在这个时候,我想确保每个将发布的产品都有一个唯一的序列号和允许具有相同名称的代码,但我包含以下错误!

> TypeError: db.collection.find is not a function <br> &nbsp; &nbsp;at
> Object.module.exports.saveProductsignup
> (/home/themis/firstapp/api/config/database.js:14:19) <br> &nbsp;
> &nbsp;at /home/themis/firstapp/api/server.js:103:21 <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 Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:312:12)
> <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)
> <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)

server.js

var express     = require('express'),
        MongoClient = require('mongodb').MongoClient,
        app = express(),
        mongoUrl= 'mongodb://localhost:27017/firstapp';
var access      = require('./config/database.js'); 
var assert      = require('assert');
var ObjectId    = require('mongodb').ObjectID;
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 port        = process.env.PORT || 8080;
var jwt         = require('jwt-simple');
// 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();


MongoClient.connect(mongoUrl, function(err, db) {
    if (err) throw 'Error connecting to database - ' + err;

        // 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.'});
            });
          }
        });

        //User authentication (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.'});
                }
              });
            }
          });
        });

        //create posts about product (POST http://localhost:8080/api/createpost)
         apiRoutes.post('/resources/createpost', function (req, res) {
            if (!req.body.issue || !req.body.SN) res.status(400).send("Please give an issue and a S/N for the product");
            else {
                access.savePost(db, req.body.issue, req.body.SN, function (err) {
                    if (err) res.status(500).send("Server error");
                    else res.status(201).send("Post Created");
                });
            }
        });

        apiRoutes.post('/resources/productsignup', function (req, res) {
            if (!req.body.name || !req.body.serialnumber) res.status(400).send("Please give a name and a Serial number for the product");
            else {
                access.saveProductsignup(db, req.body.name, req.body.serialnumber, function (err) {
                    if (err) res.status(500).send("Server error");
                    else res.status(201).send("Post Created");
                });
            }
        });

        //restricted log in (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;
              }
            };



//demo Start

        apiRoutes.delete('/resources/productinfo/:id', function(req, res, next) {
            Products.findByIdAndRemove(req.params.id, req.body, function(err, post){
                if (err) return next(err);
                res.json(post);
            });
        });


        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(db, req.param('name'), function(info) {
                  if (!products) res.status(500).send("server error");
                  else res.status(200).send(info);
                    });
                }
             });


//demo End












        // 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.savePost = function (db, issue, SN, callback) {
    db.collection('posts').save({
        issue: issue,
        SN: SN
    }, callback);
};

module.exports.saveProductsignup = function (db, name, serialnumber, callback) {
    db.collection.find({ "serialnumber" : { $exists : true, $ne : null } })
    db.collection('products').save({
        name: name,
        serialnumber: serialnumber
    }, callback);
};


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

1 个答案:

答案 0 :(得分:0)

database.js module.exports.saveProductsignup中的db.collection.find({ "serialnumber" : { $exists : true, $ne : null } })输入错字:

db.collection('products').find({ "serialnumber" : { $exists : true, $ne : null } })
应该是:
L = [[1, 2, -3], [4, 5, -6], [7, 8, -9]] ... ---> 1 2 -3, 4 5 -6, 7 8 -9 A = [] for i in range(len(L)): for k in L[i]: A.append(str(k)) print(" ".join(A)) ---> 1 2 -3 4 5 -6 7 8 -9