Sunday, 30 April 2017

Showing collection using Mongoose and Express returns empty

I am trying to display the information of my database but instead of showing the contents of the collection 'users' it prints '[]'. When attempting to go to http://localhost:27017/users the readyState returns 1 but I am not quite sure it is connecting to MongoDB correctly. Any suggestions?

var express=require("express");
var http=require("http");
var path=require("path");
var db = require('./db');
var dbLink=require("./json/config.json");
var url = dbLink.devServer.url;
var bodyParser = require('body-parser');
var publicPath=path.resolve(__dirname,"public");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mon = mongoose.createConnection('mongodb://localhost:27017/db');
var app=express();

app.use(express.static(publicPath));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(require('./routers/signupServer'));

db.connect(url, function(err) {
        if (err) {
        console.log('Unable to connect to Mongo.');
        process.exit(1)
    }
    else 
    {
        var listener=http.createServer(app).listen(process.env.PORT||27017);
        console.log('Server is listening at port '+listener.address().port);
    }
});

mongoose.model('users', {username: String}, 'users');

app.get('/users', function(req, res) {
console.log(mongoose.connection.readyState);
mongoose.model('users').find(function(err, results) {
        res.send(results);
    });
});  



via jkh604

No comments:

Post a Comment