How to Count API Calls using Node.js/Express.js and Mongodb - javascript

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
}
});

Related

mongoDB collection creation

i have a problem with adding a collection into my database in mongodb atlas.
I have managed to import this collection before but i accidentally deleted it and now i can't upload it again. there is no error in my terminal. There for i don't know what is wrong with my code.. (image of my code and terminal are attached below)
There is anyone who might know why is this can happen?
EDIT
I tried to open a new database and my all the collections was imported to it and once again, only the product collection doesn't
//////////////////////////////////
/* require('dotenv').config({ path: '/.env' }) */
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '..', '.env') })
console.dir(process.env.MONGO_URI)
const mongoose = require('mongoose')
const connectDB = async () => {
try {
mongoose.connect(process.env.MONGO_URI, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('MongoDB connection SUCCESS')
} catch (error) {
console.error('MongoDB connection FAIL')
process.exit(1)
}
}
console.dir(process.env.MONGO_URI)
module.exports = connectDB
////////////////////////////////////////////////////////////////
require('dotenv').config()
const productsData = require('./data/products')
const connectDB = require('./config/db')
const Product = require('./models/product')
connectDB()
const importData = async () => {
try {
/* Product.deleteMany({}) */
Product.insertMany(productsData)
console.dir('Data Imported Successfuly')
process.exit()
} catch (error) {
console.log(error)
console.error('Error Ocured In Imported Data Process', error)
process.exit(1)
}
}
importData()
my model schema
const mongoose = require('mongoose')
const products = require('../data/products')
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
module.exports = mongoose.model('Products', productSchema)
my code and terminal image
Product.insertMany(productsData) returns a promise, but you aren't waiting for that promise to finish before exiting the process. Add an await before it and you should be okay.
Try this to create your schema instead
const { Schema } = mongoose;
const productSchema = new Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
const Product = mongoose.model("Product", productSchema);
Product.createCollection();

Passport JS Local Strategy not being called at all, login and authentication only working for one mongoose model

I have been struggling with this issue for more than a day now. I am building a backend API for a food delivery web and mobile app.
I have setup passport with the local strategy to authenticate my users.
I have two different types of users currently 1. Subscribers 2. Restaurants each using their own mongoose model (shown in my code below)
I initially set everything up for subscriber registration login, authentication sessions and cookies, all was working fine.
I then moved on to setting up passport for my Restaurant users so that a a restaurant would be able to login to their profile and make various changes to their restaurant and its listings etc.
What I found was that I was able to create an account for the Restaurant user but when trying to log the user in passport would consistently return "Unauthorized", when trying to us isAutheticated() I got the same response back. Passport would however happily keep creating restaurant users every time I hit my register endpoint. A Restaurant user would appear in my database but when trying to log them in and store a cookie, I would just get returned "unauthorized".
With Subscribers all works fine, I have check authentication on my restricted endpoints, register new Subscribers and login subscribers with 0 issues.
Through my testing I have realized a couple things
Passport doesn't make use of the local strategy at all, I can literally black the whole thing out and it will still register subscribers log them in and check authentication via cookies with 0 issues. When placing a console.log into the strategy I can see the strategy is literally not being called at all. How could this be happening, surely passport needs the strategy in order to do its job? In this case its seems not, WHY?
Initially I tried to create a separate strategy for each of my Models, one strategy for Subscribers and one strategy for Restaurants using .createStrategy() this returned the same issue, all functionality for Subscriber model users worked fine but as soon as I tried to login or store a cookie for a user from my Restaurant model passport would just return "Unauthorized. Then you will see in the below code under server.js that I tried to create one local strategy and then build an if else in so passport checks both Subscriber and Restaurant models, through doing this I realized passport wasn't using the strategy at all.
I am ready to tear my hair out at this point what is the point of creating a strategy is passport is somehow just bypassing it completely. If I try to log a Subscriber in with the wrong credentials passport does its job and doesn't allow access so how is it actually managing authentication?
Below is my code, anyone who could help with this would more than make my day!
Server.js:
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors")
const bodyParser = require("body-parser");
const passport = require("passport");
const session = require("express-session");
const LocalStrategy = require('passport-local').Strategy;
mongoose.connect(process.env.DATABASE_URL)
const db = mongoose.connection
db.on("error", () => console.error(error))
db.once("open", () => console.log("connected to database"))
// app.use(express.json())
// Use JSON parser for all non-webhook routes
app.use((req, res, next) => {
// console.log(req.originalUrl)
if (req.originalUrl === "/subscribers/webhook") {
next();
} else {
bodyParser.json()(req, res, next);
}
});
app.use(cors())
//INITIAL STRATEGY i TRIED
// passport.use(new LocalStrategy(
// function (username, password, done) {
// Subscriber.findOne({
// username: username
// }, function (err, user) {
// if (err) {
// return done(err);
// }
// if (!user) {
// return done(null, false);
// }
// if (!user.verifyPassword(password)) {
// return done(null, false);
// }
// return done(null, user);
// });
// }
// ));
app.use(session({
secret: "foodsecrets",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// sTRATEGY i WROTE TO TRY SEPERATE THE MODELS BEFORE I REALIZED THE STRATEGY WAS NOT BEING CALLED AT ALL
passport.use(new LocalStrategy(function (username, password, done) {
Subscriber.findOne({
username: username,
password: password
}, function (err, user) {
console.log("called")
// first method succeeded?
if (!err && user && passwordMatches(password)) {
return done(null, user);
}
// no, try second method:
Restaurant.findOne({
name: username,
password: password
}, function (err, user) {
// second method succeeded?
if (!err && user && passwordMatches(password)) {
return done(null, user);
}
// fail!
done(new Error('invalid user or password'));
});
});
}));
const subscribersRouter = require("./routes/subscribers")
const restaurantsRouter = require("./routes/restaurants")
const ordersRouter = require("./routes/orders")
const seederRouter = require("./routes/seeder");
app.use("/subscribers", subscribersRouter)
app.use("/restaurants", restaurantsRouter)
app.use("/orders", ordersRouter)
app.use("/seeder", seederRouter)
app.listen(3000, () => {
console.log("Server has started on port 3000")
});
Subscriber Model:
const mongoose = require("mongoose")
const passportLocalMongoose = require("passport-local-mongoose");
const cartSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
categories: {
type: Array,
required: true
},
rating: {
type: String
},
restaurantname: {
type: String
}
});
const favouritesSchema = new mongoose.Schema({
favouritemeals: {
type: Array
},
favouriteresturants: {
type: Array
}
});
const pendingItemsSchema = new mongoose.Schema({
name: String,
price: Number,
description: String
});
const pendingOrderSchema = new mongoose.Schema({
userID: {
type: String,
required: true
},
total: {
type: Number,
required: true
},
items: [pendingItemsSchema],
removeItem: {
type: String
},
orderData: {
type: Date,
required: true,
default: Date.now
},
status: {
type: String
}
});
const subscriberSchema = new mongoose.Schema({
googleID: {
type: String
},
facebookID: {
type: String
},
username: {
type: String,
required: true
},
email: {
type: String,
},
subscribeData: {
type: Date,
required: true,
default: Date.now
},
orderHistory: {
type: Array,
},
favourites: {
favouritesSchema
},
cart: [cartSchema],
login: {
type: String,
},
pendingOrder: [pendingOrderSchema],
stripeCustId: {
type: String,
required: true
},
role:{
type: String,
// required: true
}
});
subscriberSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("subscriber", subscriberSchema);
Subscribers.js all required
const express = require("express");
const router = express.Router();
const Subscriber = require("../models/subscriber");
const Restaurant = require("../models/restaurant");
const passport = require("passport");
const Order = require("../models/order");
const bodyParser = require("body-parser");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const facebookStrategy = require('passport-facebook').Strategy;
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET
// passport.use(Subscriber.createStrategy());
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
Subscriber.findById(id, function (err, user) {
done(err, user);
});
});
Subscribers.js Login endpoint:
// LOGIN USING PASSPORT JS
router.post("/login", (req, res) => {
const subscriber = new Subscriber({
username: req.body.username,
password: req.body.password,
email: req.body.email
});
req.login(subscriber, async function (err) {
if (err) {
console.log(err)
} else {
try {
passport.authenticate("LocalStrategy")(req, res, function () {
console.log("Authenticated")
res.status(201).json("authenticated")
})
} catch (err) {
res.status(400).json({
message: err.message
})
}
}
})
})
Subscribers.js Register Endpoint:
// REGISTER USING PASSPORT JS
router.post("/register", async (req, res) => {
const customer = await stripe.customers.create({
name: req.body.username,
email: req.body.email
});
console.log("customer", customer)
Subscriber.register({
username: req.body.username,
email: req.body.email,
stripeCustId: customer.id
}, req.body.password, async (err, subscriber) => {
if (err) {
console.log(err)
} else {
try {
await passport.authenticate("local")(req, res, function () {
console.log("is authenticated")
res.status(201).json(newSubscriber)
})
const newSubscriber = await subscriber.save()
} catch (err) {
res.status(400).json({
message: err.message
})
}
}
});
})
Restaurant Model:
const mongoose = require("mongoose")
const passportLocalMongoose = require("passport-local-mongoose");
const menueItemSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
categories: {
type: Array,
required: true
},
rating: {
type: Number
},
restaurantname: {
type: String
}
})
const activeOrderSchema = new mongoose.Schema({
userID: {
type: String,
required: true
},
total: {
type: Number,
required: true
},
items: [menueItemSchema
],
orderData: {
type: Date,
required: true,
default: Date.now
},
status: {
type: String
}
})
const restaurantSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
},
src: {
type: String,
required: true
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
menue: [menueItemSchema],
rating: {
type: String
},
categories: {
type: String
},
subscribeData: {
type: Date,
required: true,
default: Date.now
},
activeOrders: [activeOrderSchema]
})
restaurantSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("restaurant", restaurantSchema)
Restaurants.js all required:
const express = require("express")
const router = express.Router()
const Restaurant = require("../models/restaurant")
const passport = require("passport");
const randomRest = require("randomrestgenerator")
// passport.use(Restaurant.createStrategy());
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
Restaurant.findById(id, function (err, user) {
done(err, user);
});
});
Restaurants.js Login endpoint:
router.post("/login", (req, res) => {
const restaurant = new Restaurant({
username: req.body.username,
password: req.body.password,
email: req.body.email
});
req.login(restaurant, async function (err) {
if (err) {
console.log(err)
} else {
try {
passport.authenticate("local")(req, res, function () {
console.log("Authenticated")
res.status(201).json("authenticated")
})
} catch (err) {
res.status(400).json({
message: err.message
})
}
}
})
})
Restaurants.js Register endpoint
// PASSPORT JS RESTAURANT REGISTRATION
router.post("/register", async (req, res) => {
const randomRestaurant = randomRest()
Restaurant.register({
username: req.body.username,
email: req.body.email,
src: randomRestaurant.img,
title: randomRestaurant.title,
description: randomRestaurant.description,
menue: randomRestaurant.menue,
rating: randomRestaurant.rating,
categories: randomRestaurant.categories
}, req.body.password, async (err, restaurant) => {
if (err) {
console.log(err)
} else {
try {
console.log("try called")
const newRestaurant = await restaurant.save()
await passport.authenticate("rest")(req, res, function () {
console.log("is authenticated")
res.status(201).json(newRestaurant)
})
} catch (err) {
console.log("here!")
res.status(400).json({
message: err.message
})
}
}
});
I managed to fix this a couple days ago, turns out I had left my JSON response outside of the passport.authenticate callback function in the restaurants login endpoint.
I moved serialize and deserialize into server.js as well as my session and passport initialization and passport session .use
Also had to setup my serialize and desearialize user functions with if elses' so that they serviced both models.
Then lastly I added an array of secrets to my session instead of just one string.
All is working fine now.
passport.serializeUser(function (user, done) {
if (user instanceof Subscriber) {
done(null, {
id: user.id,
type: "Subscriber"
});
console.log("sub user")
} else {
console.log("rest user")
done(null, {
id: user.id,
type: "Restaurant"
})
}
});
passport.deserializeUser(function (id, done) {
console.log("de-serialize called")
console.log("id type", id.type)
console.log("ID", id)
if (id.type === "Subscriber") {
Subscriber.findById(id.id, function (err, user) {
done(err, user);
})
} else {
Restaurant.findById(id.id, function (err, user) {
done(err, user);
})
}
});

Mongoose are returning undefined value of property

Well, I'm trying to get a value of property from a object with Mongoose find(), but for some reason, the mongoose are returning a undefined value.
The Schema:
const mongoose = require('mongoose');
const uuid = require('uuid');
const Schema = mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", Schema);
module.exports = Members;
The code
// Database connection
mongoose.connect(DATABASE.uri, DATABASE.options);
Members.find({ 'dsID': dsID }, (err, member) => {
const connected = member.mcConnected;
console.log(connected)
});
This might be because of you should not name a model 'Schema'. Try with other name because "Schema" is reserved word
Use this code on schema
const mongoose = require('mongoose');
const uuid = require('uuid');
const memberSchema = new mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", memberSchema);
module.exports = Members;
Here u go boys:
const app = express()
const port = 3000
//MongoDB Connection
const DB_Connect = require('./(8.1)MongoDB_Connection')
const DB = DB_Connect() //returning a Model
//Middleware
const logger = function(req, res, next) {
console.log('logging')
next()
}
app.use(logger)
//Routes
app.get('/', async(req, res) => {
console.log(DB.then((docs) => {
console.log(docs.find({ name: 'POCO X3 Pro' }, (error, docs) => {
if (error) {
console.log("Error: " + error)
} else {
console.log(docs)
}
}))
}))
})
/*
DB is a Model and console.log(DB) gives : " Promise { Model { users } } ".
But for Promise we use .then() for result.
Model { users }
As we use .find(), we got the answer
*/
//Listening
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
//Muhammad Irtaza Ghaffar (Pakistan)
Thanks me later!

node js get doesnt get anything

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

schema is not a constructor

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');

Categories