I have created a dynamic schema for every user with node and mongoose as given below.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;
var values = 'Credit Debit'.split(' ');
var schema = new Schema({
amount: {
type: Currency,
required: true
},
type: {
type: String,
enum: values
},
description: {
type: String,
required: true
}
},
{
timestamps: true
});
exports.create_database = function(mobile) {
return mongoose.model('personal_'+mobile, schema, 'personal_'+mobile);
};
I have used this in a personal router code given below
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var database = require('../models/personal');
var Verify = require('./verify');
var personalRouter = express.Router();
personalRouter.use(bodyParser.json());
personalRouter.route('/')
.get(Verify.verifyOrdinaryUser, function (req, res, next) {
var mobile = req.decoded._doc.mobile;
var Personal = database.create_database(mobile);
Personal.find(req.query)
.exec(function (err, personal) {
if (err) next(err);
res.json(personal);
})
})
.post(Verify.verifyOrdinaryUser, function(req, res, next) {
var mobile = req.decoded._doc.mobile;
var Personal = database.create_database(mobile);
Personal.create(req.body, function(err, personal) {
if(err) next(err);
console.log('Personal Record added!');
var type = personal.type;
var amount = personal.amount/100;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the '+type+' record of amount = '+amount);
})
})
module.exports = personalRouter;
Now everything works good withe the get and the post routers untill i pass in values which do not go with the mongoose schema.
Eg. If i pass in the value as say without a description my server will give a validation error and crash.
I tried replacing next(err) with throw(err in the code without any luck.
I want the error to be displayed and prevent the server from crashing and shutting down.
Please help me, where am i going wrong?
Related
I am trying to get data from mongodb to show in a table but not working.I am new in nodejs so anyone can help to find a solution?
If i open this url i am getting like this:
http://localhost:3000/api/getTableData
{"status":true,"table":{}}
table.modal.js:
const mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
product_name: {
type: String
},
price: {
type: String
},
catogery: {
type: String
}
});
mongoose.model('table', userSchema);
table.controller.js:
const mongoose = require('mongoose');
const passport = require('passport');
const _ = require('lodash');
const Table = mongoose.model('table');
var table = new Table();
/*Get Table Data*/
module.exports.getTableData = (req, res, next) => {
Table.find({ _id: req._id },
(err, table) => {
if (!table)
return res.status(404).json({ status: false, message: 'Table data records not found.' });
else
return res.status(200).json({ status: true, table: _.pick(table, ['product_name', 'price', 'category']) });
}
);
}
index.router.js:
const express = require('express');
const router = express.Router();
const ctrlTable = require('../controllers/table.controller');
router.get('/getTableData', ctrlTable.getTableData);
module.exports = router;
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
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!');
}
});
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);
}
});
});
[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.