How can we add collections in mongoDB dynamically( through users)? - javascript

Adding collections manually is easy but adding it dynamically giving me unexpected answer.
I am getting a collection name from frontend to backend using promt and axios but when I am doing
const variable_from_frontEnd = mongoose.model(variable_from_frontEnd, Schema);
it is not adding any collections.
import express from "express";
import mongoose from "mongoose";
import Messages from "./messages.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
const pusher = new Pusher({
appId: "1183689",
key: "c9fa659fc6b359a23989",
secret: "9da56a5db535e10c7d95",
cluster: "eu",
useTLS: true
});
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:zoe6B82AZjaLXgw7#cluster0.zp9dc.mongodb.net/Whatsapp_MERN?retryWrites=true&w=majority";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
const groupSchema = mongoose.Schema( {
message: String,
name: String,
timestamp: String,
received: Boolean,
});
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await Messages.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new personalGroup(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// route for creating new collection in mongoDB
app.post("/room/new", async (req, res) => {
try{
let groupName = req.body.room;
groupName = mongoose.model(groupName, groupSchema);
if(!groupName){
console.log("error is occured");
}else{
console.log(groupName);
}
}
catch(err){
res.status(400).send(err);
}
})
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
Let's say I have type a collection name "studyGroup" from frontend then
console is giving me
Model { studyGroup }
Can someone help me why it is happening and how can I add collections manually.

Related

Firebase functions can't access my middleware routes

///index.js
const functions = require("firebase-functions");
const express = require("express");
const app = express();
const productRouter = require('./routes/productRoutes');
const globalErrorHandler = require('./controllers/errorController');
const AppError = require('./utils/appError');
// Compressing upcompressed files which is been sent to client such text.
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.send('Hello World')
});
app.get('/homepage', (req, res) => {
res.send('Hello People of God')
});
app.use('/products', productRouter);
// Handing Unhandled Routes
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
app.use(globalErrorHandler);
exports.app = functions.https.onRequest(app);
///productRoutes.js
const express = require('express');
const {
getProduct,
getAllProduct,
} = require('./../controllers/productController');
const router = express.Router();
router
.route('/')
.get(getAllProduct);
router
.route('/:id')
.get(getProduct);
module.exports = router;
///productController.js
const AppError = require('../utils/appError');
const Product = require('../modals/productModels');
const catchAsync = require('../utils/catchAsync');
// GET SINGLE PRODUCT CONTROLLER
exports.getProduct = catchAsync(async (req, res, next) => {
const product = await Product.findById(req.params.id)
.populate('reviews');
if (!product) {
return next(new AppError('No product found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
product
}
});
});
// GET ALL PRODUCT CONTROLLER
exports.getAllProduct = catchAsync(async (req, res, next) => {
const products = await Product.find();
res.status(200).json({
status: 'success',
results: products.length,
data: {
products
}
});
});
///server.js
const mongoose = require('mongoose');
const app = require('./index')
const dotenv = require('dotenv');
// CONNECTING TO MONGODB SERVER
dotenv.config({ path: './config.env' })
const DB = process.env.DATABASE.replace('<PASSWORD>', process.env.DATABASE_PASSWORD);
mongoose.connect(DB, {
useNewUrlParser: true,
safe: true,
strict: false,
useUnifiedTopology: true
}).then(con => console.log('DB connection successful'))
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
After running function serve on my terminal i can access the two '/' and 'homepage' app.get which return the res "Hello world" and "Hello people of God" but can't access app.use('/products', productRouter). Its does take some time to run and throw an error "{"code":"ECONNRESET"}" please why is this so.
Am expecting to get my list of products from my mongodb data base.

How can I get the data of particular collection of mongodb?

In the below cole, in 4th line, Messages is my collection name of mongodb which I created on other file. And if I find the data of this collection then no error is occuring.
But when I am writing other collection name of mongodb which I created manually on mongodb website then it is giving error.
import express from "express";
import mongoose from "mongoose";
import Pusher from "pusher";
import Messages from "./messages.js";
import dynamicModel from "./messagesRoom.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:zoe6B82AZjaLXgw7#cluster0.zp9dc.mongodb.net/Whatsapp_MERN";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await other__collection.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new Messages(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
My question is how can I get the data of other collections of mongoDB in the same way as I am getting with the collection which I made on other file
This is my Message collection.
import mongoose from "mongoose";
const messageSchema = mongoose.Schema( {
message: String,
name: String,
timestamp: String,
received: Boolean,
});
const messageContent = mongoose.model('messageContent', messageSchema);
export default messageContent;
Since you are using mongoose, you have to create a Schema and a Model for each collection, and then you can query MongoDB with that Model.
So, create a Schema and a Model for that other collection like you did with messageContent and use that Model when you query DB.

MongoDB Returns Empty Error Object when Making POST Request

I'm currently learning about APIs. I'm using Dev Ed's video on a RESTful MERN API. I set up my routes and I could successfully connect to my MongoDB database. However, when attempting to call save() on a post to the DB, I was returned my error message, a JSON object with a message containing the err, but my err object was completely empty.
posts.js:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('We are on /posts!');
});
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({ message: err });
});
});
module.exports = router;
app.js:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true },
() => {
console.log('Succesfully connected to DB!')
});
app.listen(PORT);
Post.js (schema):
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
}
});
module.exports = mongoose.model('Posts', PostSchema);
My POST request and response (Postman):
In my code, I am attempting to send the new Post to my DB, but instead I get an error, an empty one. I either need to figure out how to view my error correctly (so that's it's not empty) or the larger problem: why my POST request is failing.
Again, I am learning about APIs, this is my very first time writing one. If there's anything I missed (like other code that you would need) or if there's something I should be doing differently, please, let me know! Thank you in advance!
use status when you want to use res like this:
for success result
res.status(200).json(data);
for .catch
res.status(500).json({ message: err });
but I prefer use async/await with try/cacth like this:
router.post('/', async(req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
try {
let data = await post.save()
res.status(200).json(data)
} catch (error) {
res.status(500).json({ message: error});
}
});
check the documentation of promises in mongnoos
check the connection of mongoose like this:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
runMongoose()
app.listen(PORT);
async function runMongoose(){
try {
await mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true }
);
console.log("mongodb is OK");
} catch (error) {
console.log("mongodb Warning", error);
}
}
if Succesfully connected to DB! printed mongoose connection is OK
the problem is that you added
{ useNewUrlParser: true }
remove that and it's gonna work fine ;)

NodeJs: Trigger API's which are in another file

I'm new to NodeJs, apologies if this query is basic one.
Implemented the API's like below and everything working fine
UserServices.js
import mongoose from "mongoose";
const createUserSchema = mongoose.Schema({
companyName: String,
email: String,
contactNumber: String,
password: String
});
export default mongoose.model("users", createUserSchema);
server.js
import express from "express";
import mongoose from "mongoose";
import Cors from "cors";
import GlobalVars from "./utils/GlobalVars";
import createUserSchema from "./apis/services/UserServices";
// App Config
const app = express();
const port = process.env.PORT || 8001;
// Middleware
app.use(express.json());
app.use(Cors());
// DB Config (Connecting DB)
mongoose.connect(GlobalVars.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
// API Endpoints
app.get("/", (req, res) => res.status(200).send("Hello World"));
app.post("/create_user", (req, res) => {
const userData = req.body;
console.log("userData " + JSON.stringify(userData));
createUserSchema.create(userData, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
app.get("/users_list", (req, res) => {
createUserSchema.find((err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(data);
}
});
});
// Listener
app.listen(port, () => console.log(`Listening on host: ${port}`));
but i don't want to mention get and post calls in the server.js, want to make server.js as clean as possible. So, would like to mention get and post calls in UserServices.js. For this, followed below structure but it's not working
UserServices.js
import mongoose from "mongoose";
import express from "express";
const app = express();
const createUserSchema = mongoose.Schema({
companyName: String,
email: String,
contactNumber: String,
password: String
});
mongoose.model("users", createUserSchema);
const createUser = () => {
app.post("/create_user", (req, res) => {
const userData = req.body;
console.log("userData " + JSON.stringify(userData));
createUserSchema.create(userData, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
};
const getUsersList = () => {
app.get("/users_list", (req, res) => {
createUserSchema.find((err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(data);
}
});
});
};
export { createUser, getUsersList };
server.js
import express from "express";
import mongoose from "mongoose";
import Cors from "cors";
import GlobalVars from "./utils/GlobalVars";
import { createUser, getUsersList } from "./apis/services/UserServices";
// App Config
const app = express();
// eslint-disable-next-line no-undef
const port = process.env.PORT || 8001;
// Middleware
app.use(express.json());
app.use(Cors());
// DB Config (Connecting DB)
mongoose.connect(GlobalVars.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
// API Endpoints
app.get("/", (req, res) => res.status(200).send("Hello World"));
createUser();
getUsersList();
// Listener
app.listen(port, () => console.log(`Listening on host: ${port}`));
My query is, how to mention API's globally or how to trigger API's which are written in another file
The problem is that you're creating two different apps here (with two calls to express()). Instead, you can just pass your app reference defined in server.js to the createUser and getUsersList functions:
// server.js
import express from "express";
import mongoose from "mongoose";
import Cors from "cors";
import GlobalVars from "./utils/GlobalVars";
import { createUser, getUsersList } from "./apis/services/UserServices";
// App Config
const app = express();
// eslint-disable-next-line no-undef
const port = process.env.PORT || 8001;
// Middleware
app.use(express.json());
app.use(Cors());
// DB Config (Connecting DB)
mongoose.connect(GlobalVars.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
// API Endpoints
app.get("/", (req, res) => res.status(200).send("Hello World"));
createUser(app);
getUsersList(app);
// Listener
app.listen(port, () => console.log(`Listening on host: ${port}`));
Then, get rid of const app = express(); in UserServices.js and have the createUser and getUserList functions accept app as a parameter:
// UserServices.js
import mongoose from "mongoose";
const userSchema = mongoose.Schema({
companyName: String,
email: String,
contactNumber: String,
password: String
});
const userModel = mongoose.model("users", userSchema);
const createUser = app => {
app.post("/create_user", (req, res) => {
const userData = req.body;
console.log("userData " + JSON.stringify(userData));
userModel.create(userData, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
};
const getUsersList = app => {
app.get("/users_list", (req, res) => {
userModel.find({/*query here if any*/}, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(data);
}
});
});
};
export { createUser, getUsersList };

Cannot get "/tinder/cards" route but getting "/" route

This below code is my first react application. After running server.js. After entering "http://localhost:8001/" I got HELLO!!. I expected after entering "http://localhost:8001/tinder/cards" url on chrome and postman too I get following error.
error message: "Cannot GET /tinder/cards".
this is my server.js file.
import mongoose from 'mongoose'
import Cors from 'cors'
import Cards from './dbCards.js'
// App Config
const app = express()
const port = process.env.PORT || 8001
const connection_url = 'mongodb+srv://admin:0tRkopC1DKm4ym4V#cluster0.iw73w.mongodb.net/tinderDB?retryWrites=true&w=majority'
// Middlewares
app.use(express.json())
app.use(Cors())
app.use('/',router);
// DB Config
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
// API Endpoints
app.get("/", (req, res) => res.status(200).send("HELLO!!"))
app.get("/hello", (req, res) => res.status(200).send("Oooooooo!!"))
app.post("/tinder/cards", (req, res) => {
const dbCard = req.body
Cards.create(dbCard, (err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get("/tinder/cards", (req, res) => {
Cards.find((err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
// Listener
app.listen(port, () => console.log(`listening on location: ${port}`)) ```
try this in your app.get('/tinder/cards') section:
// Doing it the Asynchronous way
app.get('/tinder/cards', async (req, res) => {
try { // Trying for getting the cards
const allCards = await Cards.find(); // Getting the cards
res.status(200).send(allCards); // Sending the cards
} catch (error) { // Catching the error
res.status(500).send(error); // Sending the error
}
});
Try to replace cards with card in the URL. Have a look at the image for the same.

Categories

Resources