Reputation: 865
I am using Node JS and MongoDb, I am trying to get data from MongoDb, but all i get is empty response even though I guess it connects to database and can access the collections.
This is my Server.js
// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8000; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var messageId = {};
// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.connection.on('error', function(e) {
console.log('Can not connect Error:>>',e);
process.exit();
});
mongoose.connection.once('open', function(d) {
console.log("Successfully connected to the database");
})
//app.use(express.static('./public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
//res.writeHead(200,{'content-type':'text/plain'});
// res.write("Sever On");
// res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
console.log('User Connected -- Server Online');
socket.on('message', function (msg,msgId) {
io.emit('message', "Hello");
console.log("message from client:", msg);
setInterval(function(){
io.emit("messageStatus",msgId);
},500)
});
});
app.use(require('./app/routes.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);
After I start my server, I always get connection successfully. I am currently running the server on localhost:8000
This is my config/database.js, I am using AWS to host my MongoDB
module.exports = {
remoteUrl : 'mongodb://username:[email protected]:27017/testdb'
};
I have created a Schema based on my MongoDB, named it as userprofile.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProfileSchema = new Schema({
id:{
type:String,
required:true
},
FirstName:{
type:String,
required:true
},
LastName:{
type:String,
required:true
},
EmailID:{
type:String,
required:true
},
Phone:{
type:Number,
required:true
},
Address1:{
type:String,
required:true
},
Address2:{
type:String,
required:true
},
PinCode:{
type:Number,
required:true
},
Gender:{
type:String,
required:true
},
ProfilePic:{
type:String,
required:true
},
IDproof:{
type:String,
required:true
},
UserName:{
type:String,
required:true
},
Password:{
type:String,
required:true
},
Dob:{
type:Number,
required:true
},
City:{
type:String,
required:true
},
State:{
type:String,
required:true
},
HighestEducation:{
type:String,
required:true
}
})
module.exports = mongoose.model('UserProfile',ProfileSchema);
This is my route.js
var express = require('express')
var app = module.exports = express.Router();
var UserProfile = require('./models/UserProfile');
app.get('/User', function (req, res) {
UserProfile.find(function (err, profile) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
return res.json({"success":false,"msg":err})
console.log(err);
}
res.status(200).send({"success":true,"result":profile})
});
});
Here i get the response as GET/User 200 and when I run localhost:8000/User I get this below, the result is empty, I am guessing it can access the Collections but not able to get data.
{"success":true,"result":[]}
In Mongo DB, I have a database named as testdb I have a collection named as User This is a sample of one the entries in the table
db.User.find().pretty()
{
"_id" : ObjectId("5a83d1400d47870303228bfa"),
"FirstName" : "Jazz",
"LastName" : "Ben",
"EmailID" : "[email protected]",
"Phone" : 7654329878,
"Address1" : "Golden Tulip Est",
"Address2" : "Earth",
"PinCode" : 500084,
"Gender" : "WhoCares",
"ProfilePic" : "hugyft.in",
"IDproof" : "hugyc.in",
"UserName" : "Jazz",
"Password" : "1736127",
"Dob" : 1071985,
"City" : "TheBest",
"State" : "Solid",
"HighestEducation" : "PHD"
}
Please help me understand where did I go wrong.
Upvotes: 0
Views: 1510
Reputation: 373
Specify the collection name in the userprofile.js
module.exports = mongoose.model('UserProfile',ProfileSchema,'User');
Upvotes: 2