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;
Related
I'm trying to add authentication to my ionic application but I get this error that I don't know how to solve it: Cannot read property 'findOne' of undefined
I want to check about the user if he exists in the database or not but for some reason, I get this error when I try the login in postman
please what I'm missing?
here the auth.js
const express = require('express');
const router = express.Router();
const mongoose = require("mongoose");
const _ = require("lodash");
const bcrypt = require('bcrypt');
const joi = require('joi');
const { DRAFBIE } = require('../employees/drafbie');
router.post('/', async (req, res) => {
let user = await DRAFBIE.findOne({ DECAFFE: req.body.DECAFFE})
if (!user) {
return res.send("employee number is wrong");
}
const checkpassword = await bcrypt.compare(req.body.MOT_PASS, user.MOT_PASS);
if (!checkpassword) {
return res.send("Invalid password");
}
res.send("welcome to your account")
});
module.exports = router;
here the drafbie.js
const express = require('express');
const mongoose=require('mongoose');
const router = express.Router();
const bcrypt = require("bcrypt");
const DRAFBIE = mongoose.model("DRAFBIE", mongoose.Schema({
DECAFFE: {
type: Number,
required: true,
minlength: [3, 'the min value is 100'],
maxlength: [5, "the max value is 9999"]
},
DELAFFE: {
type: String,
required: true
},
TYPE: {
type: String,
required: true,
maxlength: 1
},
AR_DELAFFE: {
type: String,
required: true
},
VLD: {
type: Number,
required: true,
max:[1,"the value of the VLD must be 0 or 1 "]
},
MOT_PASS:{
type: String,
required: true,
},
DEMAIL: {
type: String,
},
NATURE: {
type: String,
maxlength: 1
}
}))
router.get("/", async (req, res) => {
const drafbie = await DRAFBIE.find().sort("DECAFFE");
res.send(drafbie);
});
router.post("/", async (req, res) => {
const drafbie = new DRAFBIE({
DECAFFE: req.body.DECAFFE,
DELAFFE: req.body.DELAFFE,
TYPE: req.body.TYPE,
AR_DELAFFE: req.body.AR_DELAFFE,
VLD: req.body.VLD,
MOT_PASS: req.body.MOT_PASS,
DEMAIL: req.body.DEMAIL,
NATURE:req.body.NATURE
})
await drafbie.save();
res.send(drafbie);
})
router.put("/:decaffe&:password", async (req, res) => {
const saltRound = 10;
const drafbie = await DRAFBIE.findOneAndUpdate({ DECAFFE: req.params.decaffe },
{
$set: {
MOT_PASS: await bcrypt.hash(req.params.password,saltRound)
}
},{new:true}
)
await drafbie.save();
res.send(drafbie)
})
async function updateallpassword() {
const saltRound = 10;
const drafbie = await DRAFBIE.updateMany({ MOT_PASS: "123456789" },
{
$set: {
MOT_PASS: await bcrypt.hash("123456789", saltRound)
}
} ,{new:true});
console.log(drafbie + " the update is done successfully");
}
//updateallpassword();
module.exports = router;
exports.DRAFBIE = DRAFBIE;
here the new error when I change :
module.exports = router; exports.DRAFBIE = DRAFBIE;
module.exports.DRAFBIE = DRAFBIE; module.exports.router = router;
You're exporting the model in the wrong way.Try to modify the last lines of your drafbie.js from :
module.exports = router;
exports.DRAFBIE = DRAFBIE;
to :
module.exports.DRAFBIE = DRAFBIE;
module.exports.router = router; // I modified it to export the router object too, it will impact the code where you import the router.
This will allow you to import the DRAFBIE model in the auth.js like you did : const { DRAFBIE } = require('../employees/drafbie');
How do you use the routes defined in your drafbie.js file?
upload.js file:
const router = require('express').Router();
let Upload_file = require('../models/upload.model');
router.route('/upload_file').get((req, res) => {
Upload_file.find()
.then(upload_file => res.json(upload_file))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
upload.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const upload_fileSchema = new Schema({
upload_file: {
_id: String,
name: String,
url: String,
mime: String
},
}, {
timestamps: true,
});
const Upload_file = mongoose.model('Upload_file', upload_fileSchema);
module.exports = Upload_file;
Other collections work perfect, but when I want to get the files json the array is empty, but I have more than one documents in the collection.
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 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?