Last active
January 17, 2018 11:55
-
-
Save jimywork/7942a28ab1fd693059b2674014d34046 to your computer and use it in GitHub Desktop.
Simple API for fetching keywords in database with express and mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
var mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost/dexter', { useMongoClient: true }); | |
mongoose.Promise = global.Promise; | |
var database = require('./models/database.js'); | |
var express = require('express'); | |
var app = express(); | |
var connection = mongoose.connection; | |
connection.on('connected', function(stats, err){ | |
console.log("Connected to mongodb server on port 27017"); | |
}); | |
connection.on('error', function(err){ | |
console.log("Error to connected to mongodb server on port 27017"); | |
}); | |
var Cert = mongoose.model("certs", database); | |
app.get('/search/', function(req, res){ | |
var query = req.query.q; | |
Cert.find({keywords: query}, function(err, certs) { | |
if (err) { | |
throw err; | |
} | |
if (req.query.q && certs.length >= 1) { | |
var keyswords = JSON.parse(JSON.stringify(certs)); | |
var total = []; | |
for (var i = 0; i < keyswords.length; i++) { | |
var certskeywords = keyswords[i]; | |
if (certskeywords.keywords.length >= 2) { | |
total.push(certskeywords); | |
} | |
} | |
res.send(util.format('%s total %d of %d', JSON.stringify(total), total.length, certs.length)); | |
} else if (certs.length <= 0) { | |
res.send("0 Results Found"); | |
} | |
else { | |
res.send("sorry we did not recognize this request!"); | |
} | |
}); | |
}); | |
app.listen(31337, function() { | |
console.log('Listenning on port 31337'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment