express server api returns empty - node.js

i am trying to get the data from mongodb using express server but all i am getting is empty array => []
However if i run the db.Goserv.find() in console i get the results right please help
here is the server.js file
var Schema = mongoose.Schema;
var schema = new Schema({
type: String,
address: String,
servicecost: String
}, { collection: 'Goserv' });
var Goserv = mongoose.model('Goserv', schema );
module.exports = Goserv ;
app.get('/api/centre', function(req, res) {
Goserv.find(function(err, centre){
if(err){
res.send(err);
} else {
res.json(centre);
console.log(centre);
}
});
});

Try this...
var Schema = mongoose.Schema;
var schema = new Schema({
type: String,
address: String,
servicecost: String
}, { collection: 'Goserv' });
var Goserv = mongoose.model('Goserv', schema );
module.exports = Goserv ;
app.get('/api/centre', function(req, res) {
Goserv.find({},function(err, centre){
if(err){
res.send(err);
} else {
res.json(centre);
console.log(centre);
}
});
});

Related

MongoDB not returning data using NodeJS driver application

I'm using mongoose to connect mongoDB. Its a nodeJS application. Right now I'm concerned to get the data and display it in my application. However, it doesn't show any error, neither it displays any data.
Here's my server file
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
const employeeRoute = require('./routes/employee.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true })
.then(() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) }
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/Employees', employeeRoute);
let port = process.env.PORT || 4000;
const server = app.listen(port, function () {
console.log('Listening on port ' + port);
})
and here's my route file
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
let employees = [];
Employees.find({}, function (err, results) {
if (err) {
console.log(err);
}
else {
employees = results;
console.log(employees)
res.json(employees);
}
})
})
module.exports = employeeRoute
and lastly my employee.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
},
{ collation: 'Employees' });
module.exports = mongoose.model('Employees', Employee)
Application runs fine without any error. Before posting it to the forum, I've double checked the db and collection names.
any suggestions
It looks like you might just need to refactor your route a little bit in order to ensure you get the results you want. For example, take a look at my following example:
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
// Extract data from the request object here in order to search for employees. For example:
const name = req.body.name;
const surname = req.body.surname;
let employees = [];
// Now perform a find on your specific data:
Employees.find({ first_name: name, last_name: surname }, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
// Or you can perform a find on all employees
Employees.find({}, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
})
module.exports = employeeRoute
As I mentioned in my comment too, your connection may need to be changed to use the correct term: useNewUrlParser
EDIT
I also noticed that in your Employee Schema, you put collation instead of collection - see below:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
}, { collection: 'employees' });
module.exports = mongoose.model('Employees', Employee)
Try that, does it make any difference?
You are doing it wrong buddy.Here's a sample way of inserting data using mongoose.
employeeRoute.route('/').get(function (req, res) {
Employees.create({your_data}) // ex: {email:req.body.email}
.then((employee)=>{
console.log(employee)
res.json(employee);
}).catch((err)=> {
console.log(err);
res.status(400).send({message: "your message"})
})
})
module.exports = employeeRoute

data is not insert in mongodb

I am beginner of nodejs and mongodb. I am inserting data to collection using mongoose ORM and model but not insert. Validation is working correct but data is not insert after filling complete data. I have not create collection in database manually. should I create collection manually in mongodb or create automatically when inserting document.
productsController
var mongoose = require('mongoose');
var db = require('../config/db_config');
var Product = require('../models/product');
//var Product = mongoose.model('Products');
var productController = {};
productController.add = function(req, res) {
var params = req.body;
if(!params) {
res.status(400).send({message: "Data can not be empty"});
}
var productData = new Product({
product_name : params.product_name,
price : params.price,
category : params.category
});
console.log(productData);
productData.save(function(err, product) {
if (err){
res.status(400).send({message:'Unable to save data! ' + err});
}else{
res.status(200).send({message:'Data has been saved! ' + product });
}
});
};
module.exports = productController;
Models code is here
var mongoose = require('mongoose');
var db = require('../config/db_config');
var Schema = mongoose.Schema;
var productSchema = new Schema({
product_name: { type: String, required: 'Product name cannot be left blank.' },
price: { type: String, required: 'Product price cannot be left blank.'},
category: { type: String , required: 'Product category cannot be left blank'},
updated_at : {type: Date, default: Date.now}
});
module.exports = mongoose.model('Products', productSchema);
routes file code is here:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Product = require('../models/product.js');
var productsController = require('../controllers/productsController');
router.post('/add',productsController.add);
module.exports = router;
DB config file
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var db = mongoose.createConnection('mongodb://localhost:27017/nodeweb', function(err,db){
if(err){
throw err;
console.log(err);
} else {
console.log('Successfully connected to database!');
}
});
module.exports = db;
I have insert controller, model and routes file code.
Please correct your method -
Controller function
exports.add = function(req, res) {
var new_product = new Products(req.body);
// you have define Products not Product
console.log(new_product);
new_product.save(function(err, product) {
console.log('add data');
if (err){
res.send(err);
}else{
res.json(product);
}
});
};
and for good practice in node js - i think you can start with express-app-generator
This Helps to make simple routing, with generic responses and in-built express middlewares with loggers.
I have resolved problem. database connection work with connect method.
mongoose.connect('mongodb://localhost:27017/nodeweb', {useMongoClient: true}, function(err,db){
if(err){
throw err;
console.log(err);
} else {
console.log('Successfully connected to database!');
}
});

How to insert new document to mongodb?

I have schema created now i want to save new document to collection but its not happening with below code, I am new to mongodb any help will be appreciated.
routes.js
var Diagram = require('./diagram');
router.post('/saveNewDiagram',function(req,res){
Diagram.save(req.body);
});
diagram.js
var diagram = require('./diagram.model');
var mongoose = require('mongoose');
var Diagram = {
update: function(req, res) {
diagram.update({
_id: req._id
}, {
$set: {
'string': req.string
}
}, function(err, result) {
if (err) {
return res.status(500).send(err);
} else {
console.log("successfully updated document");
}
});
},
save: function(req, res) {
var newDiagram = new diagram();
newDiagram.save(req.body);
}
}
module.exports = Diagram;
model.js
var DiagramSchema = new mongoose.Schema({
text: String,
owner: {type: String, ref:'User'},
groups: [{type: String, ref: 'Group'}],
users: [{type: String, ref: 'User'}],
string: String
});
module.exports=mongoose.model('Diagram', DiagramSchema);
You did wrong in save function, you save function should be like
save: function(req, res) {
var newDiagram = new diagram(req.body);
newDiagram.save();
}
and make sure req.body only have string and/or text fields. You may like to add following check
save: function(req, res) {
var diagramData = {
string: req.body.string,
text: req.body.text
}
var newDiagram = new diagram(diagramData);
newDiagram.save();
}

mongoose doesn't return the output with findById

I m learning nodejs and mongodb altogether with getting MEAN application
my system specifications are
ubuntu 16.04 (64 bit)
node v 6.1.0
npm v 3.8.6
"mongodb": "^2.1.18",
"mongoose": "^4.4.16",
So far I have created schema and add an entry in mongodb collection through terminal using db.locations.save() and get the generated document _id with db.locations.find().
db.locations.find().pretty() in terminal returns below output
{
"_id" : ObjectId("57428745e89f5c55e1d057dc"),
// and many other path
}
Now when I open /api/locations/57428745e89f5c55e1d057dc in browser, it neither gives result nor end the request. permanently show loading.. when testing with postman.
even tried with wrong Id than it returns proper error
{"message":"Cast to ObjectId failed for value
\"57428745e89f5c55e1d057dca\" at path
\"_id\"","name":"CastError","kind":"ObjectId","value":"57428745e89f5c55e1d057dca","path":"_id"}
and with correct id
console.log(mongoose.Types.ObjectId.isValid(req.params.locationid)); // return true
even tried
findOne({"_id": mongoose.Types.ObjectId(req.params.locationid) })
But no results
What could be the issue? Is there any bug in mongoose or anything missing .Below are my basic files with required code
loc8r/app.js
require('./app_api/models/db');
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);
loc8r/app_api/models/db.js
var mongoose = require( 'mongoose' );
var mongoURI = 'mongodb://localhost/loc8r';
var mongoDB = mongoose.createConnection(mongoURI);
mongoDB.on('connected', function (){
console.log('mongoose connected to ' + mongoURI);
});
require('./locations');
loc8r/app_api/models/locations.js
var mongoose = require( 'mongoose' );
var openingTimeSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});
var reviewSchema = new mongoose.Schema({
author: String,
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: String,
createdOn: {type: Date, "default": Date.now}
});
var locationSchema = new mongoose.Schema({
name: {type: String, required: true},
address: String,
rating: {type: Number, "default": 0, min: 0, max: 5},
facilities: [String],
coords: {type: [Number], index: '2dspehere'},
openingTime: [openingTimeSchema],
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);
loc8r/app_api/router/index.js
var express = require('express');
var router = express.Router();
var ctrlLocations = require('../controllers/locations');
/* Locations pages */
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
loc8r/app_api/controllers/locations.js
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
module.exports.locationsReadOne = function (req, res) {
if(req.params && req.params.locationid) {
Loc
.findById(req.params.locationid)
.exec(function(err, location) {
if(err) {
sendJsonResponse(res, 404, err);
return;
}
if (!location) {
sendJsonResponse(res, 404, {"message": "locationid not found"});
return;
}
sendJsonResponse(res, 200, location);
});
} else {
sendJsonResponse(res, 200, {"message": "no location id in request"});
}
}
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
I was having a similar issue, so I updated my Model file. For e.g.
const workoutsSchema = new Schema({
_id: mongoose.ObjectId,
email_add: String,
workout_date: String,
workout_duration: String
});
In the controller:-
router.route("/workouts/:id").get(function(req, res) {
console.log("Fetch Workouts of="+req.params.id);
var id = new mongoose.Types.ObjectId(req.params.id);
Workouts.findById(id, function(err, workout) {
if (err)
res.send(err)
res.json(workout);
});
});
1. console your req.params before if
loc8r/app_api/controllers/locations.js
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
module.exports.locationsReadOne = function (req, res) {
console.log(req.params)
if(req.params && req.params.locationid) {
Loc
.findById(req.params.locationid)
.exec(function(err, location) {
if(err) {
sendJsonResponse(res, 404, err);
return;
}
if (!location) {
sendJsonResponse(res, 404, {"message": "locationid not found"});
return;
}
sendJsonResponse(res, 200, location);
});
} else {
sendJsonResponse(res, 200, {"message": "no location id in request"});
}
}
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
if params empty, or console not work, then check your route path
or
console something inside sendJsonResponse, maybe your function not work. Because if permanently show loading, it mean you dont send response.
or
Try to update mongodb to latest version, maybe mongoose work not correct with mongodb 2.1.18. It`s realy very old version.
get the solution from mongoose documentation
Important! If you opened a separate connection using
mongoose.createConnection() but attempt to access the model through
mongoose.model('ModelName') it will not work as expected since it is
not hooked up to an active db connection. In this case access your
model through the connection you created:
so changing the way I create the connection
//var mongoDB = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI);
also need to comment all other functions/expression which use mongoDB variable
Alternative approach : ( if you do not want to change mongoDB in db.js )
in controllers/locations.js
change var Loc = mongoose.model('Location'); with below line
var conn = mongoose.createConnection('mongodb://localhost/loc8r');
var Loc = mongoose.model('Location');
try rewrite location controller like this
var mongoose = require('mongoose'),
Location = mongoose.model('Location');
exports.locationsReadOne = function (req, res) {
if (req.params && req.params.locationid)
Location.findById(req.params.locationid, function (err, location) {
if (err) return res.status(500).send(err);
if (location) return res.status(200).json(location);
return res.status(404).json({"message": "locationid not found"})
})
else
return res.status(200).json({"message": "no location id in request"})
}
Hey try by converting your id to object id
var mongoose = require('mongoose'),
Location = mongoose.model('Location');
exports.locationsReadOne = function (req, res) {
if (req.params && req.params.locationid)
Location.findById(mongoose.Types.ObjectId(req.params.locationid), function (err, location) {
if (err) return res.status(500).send(err);
if (location) return res.status(200).json(location);
return res.status(404).json({"message": "locationid not found"})
})
else
return res.status(200).json({"message": "no location id in request"})
}

reference and populate issue

[Solved - silly mistake in the model]
I have been trying to refer and populate in mongoose and expressjs, but its not working at all. I have followed these:
1. Mongoose examples
2. Mongoose populate
I created three files:
1) models/profile.js
var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var profileSchema = new Schema({
name: String
});
module.exports = mongoose.model('Profile', profileSchema);
2) models/work.js
var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var workSchema = new Schema({
title: String,
creditsFor: [{type: Schema.Types.ObjectId, ref: 'profile'}],
});
module.exports = mongoose.model('Work', workSchema);
3) controllers/work.js
var Work = require('../models/work.js'), fs = require('fs'), mongoose = require('mongoose');
......
exports.create = function(req, res) {
credits = [];
credits.push(mongoose.Types.ObjectId('5174a9ec993af25b01000003')); // I already created a 'Profile' and copy-pasted the _id
var work = {
title: req.body.title,
creditsFor: credits
}
var workObj = new Work(work);
workObj.save(function(err, data) {
if(err) {
throw err;
} else {
req.flash('info', 'Work item saved.');
res.redirect('/work/' + data._id);
}
});
}
.......
exports.show = function(req, res) {
var work = req.params.work;
Work.findOne({_id: work})
.populate('creditsFor')
.exec(function(err, data) {
if(err) {
throw err;
} else {
console.log(data);
res.render('site/work/show', {work: data, message: req.flash('info')});
}
});
}
When using populate(), returned creditsFor is null. When I comment populate(), it is a string(?), like this:
{
title: 'My Title',
creditsFor: '5174a9ec993af25b01000003'
}
Couldn't figure out whats going wrong. I tried to bring both the models in a single file, still nothing.

Resources