Mongodb nodejs Check if exists
<p>i'm trying to make an api which stores products and users!
at this time i want to make sure that the product which will be posted each has a unique Serial number and the code that will allow to have the same name, but i encouter the following error!</p>

<pre><code>&gt; TypeError: db.collection.find is not a function &lt;br&gt; &amp;nbsp; &amp;nbsp;at
&gt; Object.module.exports.saveProductsignup
&gt; (/home/themis/firstapp/api/config/database.js:14:19) &lt;br&gt; &amp;nbsp;
&gt; &amp;nbsp;at /home/themis/firstapp/api/server.js:103:21 &lt;br&gt; &amp;nbsp;
&gt; &amp;nbsp;at Layer.handle [as handle_request]
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at next
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at Route.dispatch
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at Layer.handle [as handle_request]
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at
&gt; /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at Function.proto.process_params
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:312:12)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at
&gt; /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at Function.match_layer
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at next
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at
&gt; /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at Function.match_layer
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at next
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at
&gt; /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
&gt; &lt;br&gt; &amp;nbsp; &amp;nbsp;at Function.match_layer
&gt; (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
</code></pre>

<p>server.js</p>

<pre><code>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 &amp;&amp; !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 &amp;&amp; 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');
        });
});
</code></pre>

<p>database.js</p>

<pre><code>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);
    });
};
</code></pre>