I am trying to build a donation form. My code is as follows
server.js
const express = require('express');
const bodyParser = require('body-parser');
var {mongoose} = require('./db/db.js');
// var {Form} = require('./models/form.js');
var {Form} = require('./models/schema.js');
var app = express();
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.send('ok');
});
//private
app.get('/form', (req, res) => {
mongoose.model('Form').find((err, form) => {
res.send(form);
});
});
//makes new member
app.post('/form', (req, res) => {
var newMember = new Form({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
phoneNumber: req.body.phoneNumber,
donation: req.body.donation,
shirt: req.body.shirt
});
newMember.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.listen(3000, () => {
console.log('Listening on port 3000.');
});
And the form model
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var formSchema = new Schema({
firstName: {
type: String,
required: true,
minlength: 1,
trim: true
},
lastName: {
type: String,
required: true,
minlength: 1,
trim: true
},
email: {
type: String,
required: true,
minlength: 1,
trim: true
},
phoneNumber: {
type: Number,
trim: true,
minlength: 7,
required: false
},
donation: {
type: Number,
required: true
},
shirt: {
type: Boolean
}
});
var form = mongoose.model('Form',formSchema);
module.exports = {form};
When I run the GET request I get all the data in the database but when I send a POST request I get the error "TypeError: Form is not a constructor
at app.post (.../server/server.js:22:19)". How do I fix this error? I think the error comes from how I am calling new Form but all the tweaks I make to the code don't seem to fix it.
You are exporting the object {form:form},note the case. But you are importing and destructuring it as Form. Change to lower case:
var {form} = require('./models/schema.js');
...
var newMember = new form({...});
Alternatively you can also map to a new varaible name while descructurting, if you want to keep it as Form:
var {form : Form} = require('./models/schema.js');
Related
This is my user schema :
import mongoose from "mongoose";
const { Schema } = mongoose;
//Address Schema
const addressSchema: mongoose.Schema = new Schema({});
//Talk about token saving planning
const userSchema: mongoose.Schema = new Schema(
{
name: {
type: String,
trim: true,
required: true,
},
username: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
required: true,
unique: true,
},
mobile_number: {
type: Number,
trim: true,
required: true,
unique: true,
},
password: {
type: String,
required: true,
min: 9,
max: 30,
},
picture: {
//AWS return object as response after upload
type: {},
//we will not provide any default
//default will be set in frontend
},
},
{ timestamps: true }
);
export default mongoose.model("User", userSchema);
Is there any way or anyone know how to create new database when newuser register in Nodejs & Express mongoose.
I am making a crm , I want to create separate database for every user who register.
var MongoClient = require('mongodb').MongoClient;
//Create a database named "userName":
userCollection.foreach(name => {
var url = "mongodb://localhost:27017/"+ name;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
}
Yes, Its possible in mySql !! and You can try it mongoose sequelize node js
const sequelizedb = new Sequelize("", MysqlInfo.username, MysqlInfo.password, {
host: MysqlInfo.dbhost,
dialect: "mysql"
});
let dbcreation = "CREATE DATABASE `" + username + "`;";
sequelizedb.query(dbcreation).then(res => {
const newDBconnection = new Sequelize(
"mysql://" +
MysqlInfo.username +
":" +
MysqlInfo.password +
"#" + MysqlInfo.dbhost + ":3306/" +
schooldbname
);
newDBconnection
.authenticate()
.then(() => {
})
I am trying to create a sample API of restaurants using POST but after starting API and loading it into Postman it does not show results.
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sample',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
restaurant.js (Controller)
const restaurants = require('../Models/restaurantData');
exports.getfilter = (req, res) => {
const city_name = req.body.city_name;
const cost = req.body.cost;
restaurants.find({
city_name: city_name,
cost: cost
}).then(result => {
res.status(200).json({
message: "Filtered Data",
result
})
}).catch(error => {
res.status(500).json({
message: error
})
})
}
restaurantData.js (Model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
I think mostly it is the router problem but trying to know where? So, share any ideas. Thank You.
This request handler:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
Does not actually call the getfilter function so nothing is ever sent from the POST request. You can fix that by either doing this:
router.post('/restaurantFilter', restaurantController.getfilter);
or this:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter(req, res);
});
Then, it looks like you also have to property export and import that getfilter() function. You appear to export it just fine in restaurant.js:
exports.getfilter = (req, res) => { ... });
But, you don't seem to be importing the controller properly as you're doing this:
const restaurantController = require('../Controllers/restaurantData');
When it looks like you should be doing this:
const restaurantController = require('../Controllers/restaurant.js');
so that you're assigning the controller the object that actually has the getfilter method on it.
I want to count all my API calls and update into my mongodb. Please find below my code I am using Express.js mongoose , In this code I fetch my APIUser info from mongodb and validate authorize user and after that increment APICall filed.
This code is working fine when API user is sending request at less rate eg. 10-20req/sec
But in real scenario i am getting large about of request eg. 1000req/sec.
Is there any way i can accurately count my API calls.
kindly replace process.env.MONGOURI with your mongodb url.
app.js -
const express = require('express');
const morgan = require('morgan');
const colors = require('colors');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
dotenv.config({ path: './config/config.env' });
const Employee = require('./models/EmployeeSchema');
const APIUser = require('./models/APIUserSchema');
mongoose.connect(process.env.MONGOURI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/addemployee', async (req, res, next) => {
var IP = req.header('X-Real-IP');
const APIClientInfo = await APIUser.findOne({
APIClientID: req.header('API-Client-ID'),
APISecretKey: req.header('API-Secret-Key'),
});
//console.log(APIClientInfo);
if (APIClientInfo) {
try {
//Copturaing API Request
const { Name, PhoneNo, Age, Department, Salary } = req.body;
const addemployee = await Employee.create(req.body);
const Response = {
Status: 'Success',
Data: addemployee,
Message: 'Successfully! Record has been inserted.',
};
APIClientInfo.APICalls++;
await APIClientInfo.save();
//Send Response
res.status(201).json(Response);
//Log
} catch (err) {
//if Valid Error Found
if (err.name == 'ValidationError') {
const messages = Object.values(err.errors).map((val) => val.message);
const Response = {
Error: {
message: messages,
},
};
res.status(400).json(Response);
} else {
const Response = {
Error: {
message: 'Internal Server Error',
},
};
res.status(500).json(Response);
//Send Error
}
}
} else {
//if API-Key is not valid
res.status(401).json({
Error: {
message: 'Unauthorized',
},
});
}
});
app.use((req, resp, next) => {
resp.setHeader('Access-Control-Allow-Headers', '*');
resp.setHeader('Access-Control-Allow-Origin', '*');
resp.removeHeader('X-Powered-By', '*');
resp.removeHeader('Server', '*');
next();
});
// Error handling
app.use((req, resp, next) => {
var error = new Error('Not Found ⛔ ');
error.status = 404;
next(error);
});
app.use((error, req, resp, next) => {
resp.status(error.status || 500);
resp.json({
Error: {
message: error.message,
},
});
});
//console.log = function(){};
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(
`Server Started in ${process.env.NODE_ENV} mode on Port ${PORT}`.white.bold
)
);
APIUser Schema -
const mongoose = require('mongoose');
const uuid = require('uuid');
const moment = require('moment-timezone');
const UserSchema = new mongoose.Schema({
_id: {
type: String,
default: uuid.v4,
},
Username: {
type: String,
index: { unique: true },
required: [true, 'Please Enter Your UserName'],
},
Password: {
type: String,
required: [true, 'Please Enter Your Password'],
},
Email: {
type: String,
index: { unique: true },
required: [true, 'Please Enter Your Email ID'],
},
APIClientID: {
type: String,
index: { unique: true },
minlength: 10,
maxlength: 40,
default: uuid.v4,
},
APISecretKey: {
type: String,
index: { unique: true },
minlength: 10,
maxlength: 40,
default: uuid.v4,
},
APICalls: {
type: Number,
default: 0,
},
CreatedAt: {
type: String,
default: function () {
return moment().tz('Asia/Kolkata').format('MMMM Do YYYY, hh:mm:ss A');
},
},
ModifiedAt: {
type: String,
default: function () {
return moment().tz('Asia/Kolkata').format('MMMM Do YYYY, hh:mm:ss A');
},
},
});
UserSchema.set('toJSON', {
transform: function (doc, ret, options) {
ret.UserRefNo = ret._id;
delete ret._id;
delete ret.__v;
},
});
module.exports = mongoose.model('APIUser', UserSchema);
EmployeeSchema.js -
const mongoose = require('mongoose');
const uuid = require('uuid');
const moment = require('moment-timezone');
const EmployeeSchema = new mongoose.Schema({
_id: {
type: String,
default: uuid.v4,
},
Name: {
type: String,
trim: true,
required: [true, 'Please Enter Your Name'],
},
PhoneNo: {
type: String,
trim: true,
required: [true, 'Please Enter Your Phone No'],
},
Age: {
type: String,
required: [true, 'Please Enter Your Employee Age'],
},
Department: {
type: String,
trim: true,
required: [true, 'Please Enter Your Department Name'],
},
Salary: {
type: String,
required: [true, 'Please Enter Your Employee Salary PA'],
},
CreatedAt: {
type: String,
default: function () {
return moment().tz('Asia/Kolkata').format('MMMM Do YYYY, hh:mm:ss A');
},
},
ModifiedAt: {
type: String,
default: function () {
return moment().tz('Asia/Kolkata').format('MMMM Do YYYY, hh:mm:ss A');
},
},
});
EmployeeSchema.set('toJSON', {
transform: function (doc, ret, options) {
ret.EmpRefNo = ret._id;
delete ret._id;
delete ret.__v;
},
});
module.exports = mongoose.model('Employee', EmployeeSchema);
Try updating the api calls value with a single function of updateOne:
await APIUser.updateOne({
APIClientID: req.header('API-Client-ID'),
APISecretKey: req.header('API-Secret-Key'),
}, {
$inc: {
APICalls: 1
}
});
So I'm currently learning how to build a Rest API with Node Js and MongoDB, so naturally I've been following some tutorials, and when the time came, I've setup an example but it doesn't work.
I have 2 main files, app.js and historic.js (model).
On app.js I have the following:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
app.use(bodyParser.json());
Historic =require('./models/historic');
// Connect to Mongoose
mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
var db = mongoose.connection;
console.log('Here');
db.on('error', function(err){
if(err){
console.log(err);
throw err;
}
});
db.once('open', function callback () {
console.log('Mongo db connected successfully');
});
app.get('/', (req, res) => {
res.send('Please use /api/historic');
});
app.get('/api/historics', (req, res) => {
Historic.getHistorics((err, historic) => {
if(err){
throw err;
}
res.json(historic);
});
});
app.listen(27017);
console.log('Running on port 27017...');
Then on my model I have the following:
const mongoose = require('mongoose');
// Historic Schema
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
const Historic = module.exports = mongoose.model('Historic', historicSchema);
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
Whenever I try to access http://localhost:27017/api/historics/ I only get: [].
I know that I have data on my DB as you can see on the image:
data on DB test
Any tips?
According to Docs http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html the callback should be at least the 2nd parameter of the .find method.
Try to replace
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
to
// Get Historics
module.exports.getHistorics = (callback, limit) => {
var query = Historic.find({});
query.limit(limit);
query.exec(callback);
}
I've been told the solution and it works.
Old Code:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
Solution:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
}, {collection: 'historic'});
I needed add the collection name that was defined on Mongoose
I've this project folder structure:
And I'm trying to import my user schema in my user ctrl but when i start nodemon users.ctrl.js gives me this error:
const {Users} = require('users.schema');
^
SyntaxError: Unexpected token
This is the user schema:
const mongoose = require('mongoose');
const validator = require('validator');
// {
// email: 'andrew#example.com',
// password: 'adpsofijasdfmpoijwerew',
// tokens: [{
// access: 'auth',
// token: 'poijasdpfoimasdpfjiweproijwer'
// }]
// }
var Users = mongoose.model('Users', {
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
required: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
module.exports = {Users}
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
Where am I wrong? Is there something that escapes me?
By default node corresponds to /node_modules where the node packages are stored. Hence use relative path names to access the file require(./filename).
I solved the problem:
On this current pc that i'm using i had node version number 5.0.7 . To use the new ecma6 features i need to install v 8.0....
After installing the version I solved the problemAfter installing the version I solved the problem